#!/usr/bin/env bash
# ollie:parallel read
# description: Delegate a mechanical subtask to a cheaper/weaker model. Returns immediately; the worker reports back to your prompt when done. Use for tasks requiring no judgment — edits, lookups, transforms, formatting.
# Args: <instruction> [id]
set -euo pipefail

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

BACKEND="${OLLIE_CASCADE_BACKEND:-openrouter}"
MODEL="${OLLIE_CASCADE_MODEL:-mistralai/devstral-small}"

die() { printf 'cascade: %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 (cascade must run inside a session)"

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

id="${2:-cascade-$(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:"worker")

[ -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 a worker agent. Read code, reason about implementation, and complete the task within its stated scope.

RULES:
1. Complete the task using whatever tools are needed.
2. Stay within scope — do not expand beyond what was asked.
3. When finished, report your result back to the parent session using PeerSubmit.
   Format:

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

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

4. After reporting the result, STOP. 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"
