#!/usr/bin/env bash
#
# agy-task — delegate a single task to an Antigravity (Gemini) subagent.
#
# Designed to be called by an orchestrating Claude agent that needs a
# second opinion or wants to offload work to a Gemini model. Runs `agy`
# headless, captures clean output, and fails loudly with actionable errors.
#
# Usage:
#   bin/agy-task [--model <id|preset>] [--timeout <dur>] [--out <file>] <prompt...>
#   echo "long prompt" | bin/agy-task --model smart
#
# Presets:
#   fast   → gemini-3.6-flash-high   (cheap, quick research/summaries)
#   smart  → gemini-3.1-pro-high     (deep reasoning, multi-file analysis)
#
# Env overrides:
#   AGY_MODEL     default model/preset (default: smart)
#   AGY_TIMEOUT   default print timeout (default: 5m)
#   AGY_BIN       path to agy binary (default: resolved from PATH)
#
set -euo pipefail

# agy runs a full agentic loop per invocation (read → reason → tool → repeat),
# so reasoning tasks routinely take several minutes. Default generously.
MODEL="${AGY_MODEL:-smart}"
TIMEOUT="${AGY_TIMEOUT:-10m}"
OUT=""
PROMPT=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --model)   MODEL="$2"; shift 2 ;;
    --timeout) TIMEOUT="$2"; shift 2 ;;
    --out)     OUT="$2"; shift 2 ;;
    -h|--help) grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *)         PROMPT="${PROMPT:+$PROMPT }$1"; shift ;;
  esac
done

# Read prompt from stdin if not passed as args (handles long/multiline prompts).
if [[ -z "$PROMPT" && ! -t 0 ]]; then
  PROMPT="$(cat)"
fi

if [[ -z "$PROMPT" ]]; then
  echo "agy-task: no prompt provided" >&2
  exit 2
fi

# Resolve model presets to concrete ids.
case "$MODEL" in
  fast)  MODEL="gemini-3.6-flash-high" ;;
  smart) MODEL="gemini-3.1-pro-high" ;;
esac

AGY="${AGY_BIN:-$(command -v agy || true)}"
if [[ -z "$AGY" ]]; then
  echo "agy-task: 'agy' not found. Install the Antigravity CLI or set \$AGY_BIN." >&2
  exit 127
fi

# Run headless. Capture stdout+stderr so we can diagnose the known failure modes.
set +e
RESPONSE="$("$AGY" -p "$PROMPT" --model "$MODEL" --print-timeout "$TIMEOUT" 2>&1)"
CODE=$?
set -e

# Known failure: headless mode auto-denies a tool that needs a permission.
if grep -q "no output produced" <<<"$RESPONSE"; then
  echo "agy-task: agy could not act — missing headless permission." >&2
  echo "  Add read_file(*), write_file(*), command(*) to:" >&2
  echo "  ~/.gemini/antigravity-cli/settings.json under permissions.allow" >&2
  exit 3
fi

if [[ $CODE -ne 0 ]]; then
  echo "agy-task: agy exited with code $CODE" >&2
  echo "$RESPONSE" >&2
  exit "$CODE"
fi

if [[ -n "$OUT" ]]; then
  printf '%s\n' "$RESPONSE" > "$OUT"
  echo "agy-task: response written to $OUT ($(wc -l <"$OUT") lines)"
else
  printf '%s\n' "$RESPONSE"
fi
