#!/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: session path (e.g. s/my-session)
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"

name=${name:-$(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 so the child always knows who spawned it.
prompt="[parent_session_id=${OLLIE_SESSION_ID}]
[session_id=${name}]
$*"

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

printf '%s\n' "$kv" > "$OLLIE/s/new" || die "failed to create session"

B="$OLLIE/s/$name"
deadline=$(( $(date +%s) + 5 ))
until [ -d "$B" ] || [ "$(date +%s)" -ge "$deadline" ]; do sleep 0.05; done
[ -d "$B" ] || die "timeout waiting for session $name"

printf '%s\n' "$prompt" > "$B/prompt" || die "failed to submit prompt"
printf '%s\n' "$B"
