#!/usr/bin/env bash
# ollie:parallel read
# description: Route a subtask to an appropriate model tier. Returns immediately; the agent reports back to your prompt when done.
# Args: <instruction> [--tier=worker|expert] [--backend=<name>] [id]
set -euo pipefail

OLLIE="${OLLIE:-$HOME/mnt/ollie}"

die() { printf 'route: %s\n' "$*" >&2; exit 1; }

[ -z "${OLLIE_SESSION_ID:-}" ] && die "OLLIE_SESSION_ID not set (route must run inside a session)"

# Parse args
tier="worker"
backend_override=""
instruction=""
id=""
for arg in "$@"; do
    case "$arg" in
        --tier=*) tier="${arg#--tier=}" ;;
        --backend=*) backend_override="${arg#--backend=}" ;;
        *) [ -z "$instruction" ] && instruction="$arg" || id="$arg" ;;
    esac
done

[ -z "$instruction" ] && die "instruction required"

case "$tier" in
    worker|expert) ;;
    *) die "unknown tier: $tier (use worker or expert)" ;;
esac

# Resolve backend: explicit flag > parent session's backend > OLLIE_BACKEND
if [ -n "$backend_override" ]; then
    BACKEND="$backend_override"
else
    BACKEND=$(grep -m1 '^backend=' "$OLLIE/s/$OLLIE_SESSION_ID/cfg" 2>/dev/null | cut -d= -f2-)
    BACKEND="${BACKEND:-${OLLIE_BACKEND:-openrouter}}"
fi

# Resolve model: OLLIE_TIER_{TIER}_{BACKEND} > legacy flat vars > hardcoded defaults
tier_upper=$(echo "$tier" | tr '[:lower:]' '[:upper:]')
backend_lower=$(echo "$BACKEND" | tr '[:upper:]' '[:lower:]')
tier_var="OLLIE_TIER_${tier_upper}_${backend_lower}"
MODEL="${!tier_var:-}"

if [ -z "$MODEL" ]; then
    # Legacy fallback
    case "$tier" in
        worker) MODEL="${OLLIE_CASCADE_MODEL:-mistralai/devstral-small}" ;;
        expert) MODEL="${OLLIE_ESCALATE_MODEL:-anthropic/claude-sonnet-4-20250514}" ;;
    esac
fi

# Agent config
case "$tier" in
    worker) agent="worker" ;;
    expert) agent="expert" ;;
esac

id="${id:-route-${tier}-$(date +%s%N)-$$}"
[ -n "$OLLIE_SESSION_ID" ] && id="${OLLIE_SESSION_ID}__${id}"

kv="name=${id}
cwd=$(pwd)
backend=${BACKEND}
model=${MODEL}
agent=${agent}"
printf '%s\n' "$kv" > "$OLLIE/s/new" || die "failed to create session"

B="$OLLIE/s/$id"
wait=0.1
for _ in 1 2 3 4 5 6 7 8; do
    [ -d "$B" ] && break
    sleep "$wait"
    wait=$(awk "BEGIN{printf \"%.2f\", $wait * 2}")
done
[ -d "$B" ] || die "timeout waiting for session $id"

prompt="[parent_session_id=${OLLIE_SESSION_ID}]
[session_id=${id}]

Complete the following task. Read code, reason about implementation, and stay within scope.

When finished, write your result to: ${OLLIE}/s/${OLLIE_SESSION_ID}/prompt
Format:

[from=${id}]
STATUS: done
SUMMARY: <what was accomplished>

On failure:
[from=${id}]
STATUS: error
REASON: <why>

After writing the result, STOP. One write, then stop.

TASK:
${instruction}"

printf '%s\n' "$prompt" > "$B/prompt" || die "failed to submit prompt"
printf 'session=%s\npath=%s\nbackend=%s\nmodel=%s\ntier=%s\n' "$id" "$B" "$BACKEND" "$MODEL" "$tier"
