#!/usr/bin/env bash
# ollie:parallel read
# description: Escalate a hard task to a stronger model. Returns immediately; the stronger model reports back to your prompt when done. Use when stuck — complex reasoning, debugging, architecture decisions.
# Args: <instruction> [id]
set -euo pipefail

SERVICE="org.ollie.SessionManager"
OBJ="/org/ollie/SessionManager"
IFACE="org.ollie.SessionManager"

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

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

dbus_call() {
    dbus-send --session --dest=$SERVICE --type=method_call --print-reply \
        $OBJ "$IFACE.$1" "${@:2}" 2>/dev/null
}

dbus_string() {
    dbus_call "$@" | awk -F'"' '/string "/{print $2; exit}'
}

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

instruction="${1:-}"
[ -z "$instruction" ] && die "instruction required"

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

# Create session via D-Bus
session_id=$(dbus_string CreateSession \
    string:"$(pwd)" string:"$BACKEND" string:"$MODEL" string:"expert")

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

# Rename to our chosen ID
dbus_call RenameSession string:"$session_id" string:"$id" > /dev/null 2>&1

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

You are an expert agent escalated to handle a task that a weaker model could not resolve. Apply rigorous reasoning to produce a correct, complete answer.

TERMINATION RULES (mandatory — follow exactly):
1. Complete the task using whatever tools are needed.
2. When finished (success or failure), report your result back to the parent session using PeerSubmit.
   Use this exact format:

   [from=${id}]
   STATUS: done
   SUMMARY: <concise answer or confirmation>

   On failure, use:
   [from=${id}]
   STATUS: error
   REASON: <why the task could not be completed>

3. After reporting the result, STOP. Do not call any more tools. Do not report again.
4. Do not retry the report. One report, then stop.

TASK:
${instruction}"

dbus_call Submit string:"$session_id" string:"$prompt" > /dev/null 2>&1 || die "failed to submit prompt"
printf 'session=%s\nbackend=%s\nmodel=%s\n' "$id" "$BACKEND" "$MODEL"
