#!/usr/bin/env bash
# u/escalate — escalate a task to a stronger model.
#
# When a weak model can't handle a task, escalate sends it to a strong model
# and returns the result inline (blocking).
#
# Usage: escalate [flags] [prompt...]
#        echo "prompt" | escalate [flags]
#
# Flags:
#   -backend B    expert backend (default: $OLLIE_ESCALATE_BACKEND or openrouter)
#   -model M      expert model (default: $OLLIE_ESCALATE_MODEL or anthropic/claude-sonnet-4-20250514)
#   -keep         keep the expert session after completion (don't auto-cleanup)
set -euo pipefail

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

BACKEND="${OLLIE_ESCALATE_BACKEND:-openrouter}"
MODEL="${OLLIE_ESCALATE_MODEL:-anthropic/claude-sonnet-4-20250514}"

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

keep=0

while [ $# -gt 0 ]; do
    case $1 in
        -backend) BACKEND=$2; shift ;;
        -model)   MODEL=$2; shift ;;
        -keep)    keep=1 ;;
        --)       shift; break ;;
        -*)       die "unknown flag: $1" ;;
        *)        break ;;
    esac
    shift
done

if [ $# -gt 0 ]; then
    prompt="$*"
elif ! [ -t 0 ]; then
    prompt=$(cat)
else
    die "prompt required"
fi
[ -z "$prompt" ] && die "empty prompt"

flags=(-backend "$BACKEND" -model "$MODEL")
[ "$keep" -eq 1 ] && flags+=(-keep)

"$BIN" "${flags[@]}" "You are an expert model escalated to handle a hard task. Apply rigorous reasoning and produce a correct, complete answer.

$prompt"