#!/usr/bin/env bash
set -euo pipefail

WORKSPACE=""
PROMPT=""
TASK_SLUG=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --workspace) WORKSPACE="$2"; shift 2;;
    --trust) PROMPT="$2"; shift 2;;
    --task-slug) TASK_SLUG="$2"; shift 2;;
    *) shift;;
  esac
done

mkdir -p "$HOME/Projects/multideal/tmp/logs"
DATETIME=$(date +%Y-%m-%d-%H-%M-%S)
if [[ -n "$TASK_SLUG" ]]; then
  LOG="$HOME/Projects/multideal/tmp/logs/$DATETIME-$TASK_SLUG.log"
else
  LOG="$HOME/Projects/multideal/tmp/logs/$DATETIME.log"
fi
# PINNED MODEL — always pass --model composer-2.5. NEVER omit it.
# An unpinned cursor-agent run falls through to cursor's interactive config default (whatever model
# the user last selected), NOT necessarily composer-2.5 — and the log would still claim composer-2.5.
# (Shipped 2026-06-09..06-15: --model was on the log string only, never on the run line.)
# DRY: build the command ONCE here; log line and run line both use "${CURSOR_ARGS[@]}" so they
# CANNOT diverge. DO NOT remove --model and DO NOT add a second standalone cursor-agent invocation.
CURSOR_ARGS=(cursor-agent --model composer-2.5 --print --output-format stream-json --stream-partial-output --workspace "$WORKSPACE" --trust "$PROMPT")
# First line of log = exact command + full prompt (%q-quoted). So log shows which tool + what it ran.
CURSOR_CMD=$(printf '%q ' "${CURSOR_ARGS[@]}")
{
  echo "=== TOOL: cursor-agent (primary) ==="
  echo "=== CMD: $CURSOR_CMD ==="
  echo "=== log: tail -f $LOG ==="
} | tee "$LOG"

run_grok() {
  local pf gcmd
  pf=$(mktemp /tmp/ca-grok-XXXXXX.txt)
  printf '%s' "$PROMPT" > "$pf"
  gcmd=$(printf 'grok --output-format streaming-json --cwd %q --always-approve -m grok-composer-2.5-fast --prompt-file %q' "$WORKSPACE" "$pf")
  {
    echo "=== TOOL: grok (FALLBACK — cursor-agent failed) ==="
    echo "=== CMD: $gcmd ==="
    echo '{"type":"system","subtype":"fallback","tool":"grok","model":"grok-composer-2.5-fast"}'
  } | tee -a "$LOG"
  grok --output-format streaming-json --cwd "$WORKSPACE" \
    --always-approve -m grok-composer-2.5-fast --prompt-file "$pf" 2>&1 | tee -a "$LOG"
  rm -f "$pf"
}

MAX_SECONDS=3480  # 58-minute ceiling
timeout --kill-after=15s "$MAX_SECONDS" "${CURSOR_ARGS[@]}" 2>&1 | tee -a "$LOG" || {
  EXIT=$?
  if [[ $EXIT -eq 124 ]]; then
    echo "=== TIMEOUT: cursor-agent hit 58-minute ceiling, falling back to grok ===" | tee -a "$LOG"
  fi
  run_grok
}
