#!/usr/bin/env bash
# description: Spawn a subagent session, submit a prompt, and return immediately. The subagent runs independently; use prompt files for coordination.
# Args: [-name NAME] [-agent A] [-backend B] [-model M] [-cwd DIR] <prompt...>
# Output: structured KV (session, path, backend, model)
set -euo pipefail

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

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

name=; agent=; backend=; model=; cwd=

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

[ $# -eq 0 ] && die "prompt required"

# Read agent name from stdin if not provided via flag and stdin is piped.
if [ -z "$agent" ] && ! [ -t 0 ]; then
    agent=$(head -1)
fi

name=${name:-$(/bin/date +%s%N)-$$}
# Prefix with parent session ID for global uniqueness.
[ -n "$OLLIE_SESSION_ID" ] && name="${OLLIE_SESSION_ID}__${name}"
cwd=${cwd:-$(pwd)}

# Prepend parent identity and plan so the child always knows who spawned it.
parent_plan=""
if [ -n "$OLLIE_SESSION_ID" ]; then
    plan_file="$OLLIE/s/$OLLIE_SESSION_ID/plan"
    [ -s "$plan_file" ] && parent_plan=$(cat "$plan_file")
fi

prompt="[parent_session_id=${OLLIE_SESSION_ID}]
[session_id=${name}]${parent_plan:+
[parent_plan_start]
${parent_plan}
[parent_plan_end]}
$*"

kv="name=${name}
cwd=${cwd}"
[ -n "$agent"   ] && kv="${kv}
agent=${agent}"
[ -n "$backend" ] && kv="${kv}
backend=${backend}"
[ -n "$model"   ] && kv="${kv}
model=${model}"

/bin/echo "$kv" > "$OLLIE/s/new" || die "failed to create session"

B="$OLLIE/s/$name"
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 $name"

/bin/echo "$prompt" > "$B/prompt" || die "failed to submit prompt"

# Clean up JIT agent config now that the server has loaded it.
# Only remove configs with the jit- prefix (generated by subagent_generate).
[[ "${agent:-}" == jit-* ]] && rm -f "$OLLIE/a/${agent}.json" 2>/dev/null || true

# Report resolved values from the live session.
resolved_backend=$(grep -m1 '^backend=' "$B/cfg" 2>/dev/null | cut -d= -f2- || echo "${backend:-default}")
resolved_model=$(grep -m1 '^model=' "$B/cfg" 2>/dev/null | cut -d= -f2- || echo "${model:-default}")
printf 'session=%s\npath=%s\nbackend=%s\nmodel=%s\n' "$name" "$B" "$resolved_backend" "$resolved_model"
