#!/usr/bin/env bash
# ollie:parallel read
# args_json: {"type":"object","required":["instruction"],"properties":{"instruction":{"type":"string","description":"Task description to route"},"tier":{"type":"string","description":"Model tier: worker (default) or expert"},"backend":{"type":"string","description":"Backend override"}}}
# ollie:prompt
# ## route
#
# Route a subtask to an appropriate model tier. Spawns a subagent that reports back.
#
# ```
# route(instruction="implement the login page")
# route(instruction="refactor auth module", tier="expert")
# ```
# ollie:end
set -euo pipefail

source "${OLLIE_TOOLS_PATH:-$(dirname "$0")}/_lib/args.sh"

die() { echo "error: $1" >&2; exit 1; }

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

instruction=$(arg_require "instruction")
tier=$(arg_get "tier" "worker")
backend_override=$(arg_get "backend" "")

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

# Resolve backend
if [ -n "$backend_override" ]; then
    BACKEND="$backend_override"
else
    parent_config=$(ollie-9p read "session/$OLLIE_SESSION_ID/cfg" 2>/dev/null || echo "")
    BACKEND=$(printf '%s\n' "$parent_config" | grep -m1 '^backend=' | cut -d= -f2-)
    BACKEND="${BACKEND:-${OLLIE_BACKEND:-openrouter}}"
fi

# Resolve model
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
    case "$tier" in
        worker) MODEL="${OLLIE_CASCADE_MODEL:-mistralai/devstral-small}" ;;
        expert) MODEL="${OLLIE_ESCALATE_MODEL:-anthropic/claude-sonnet-4-20250514}" ;;
    esac
fi

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

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

# Create session via 9P
session_id=$(printf 'name=%s\ncwd=%s\nbackend=%s\nmodel=%s\nagent=%s\n' \
    "$id" "$(pwd)" "$BACKEND" "$MODEL" "$agent" | ollie-9p write session/new 2>&1)

[ -z "$session_id" ] && die "failed to create session"

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, report your result back to the parent session.
Format:

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

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

After reporting the result, STOP. One report, then stop.

TASK:
${instruction}"

# Find agent in new session and submit prompt
new_agent=$(ollie-9p ls "session/$id/agent" 2>/dev/null | grep -v '^new$' | head -1)
[ -z "$new_agent" ] && die "no agent created in session"

echo "$prompt" | ollie-9p write "session/$id/agent/$new_agent/prompt" 2>&1 || die "failed to submit prompt"
printf 'session=%s\nbackend=%s\nmodel=%s\ntier=%s\n' "$id" "$BACKEND" "$MODEL" "$tier"
