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

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

# Only id the grok CLI accepts (verify with `grok models`). Override when that changes.
GROK_MODEL="${CA_GROK_MODEL:-grok-4.5}"

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[@]}")

# $1 = why grok is running, for the log header.
run_grok() {
  local pf reason
  reason="$1"
  pf=$(mktemp /tmp/ca-grok-XXXXXX.txt)
  printf '%s' "$PROMPT" > "$pf"
  # Same DRY rule as CURSOR_ARGS: one array, so the logged command and the run line cannot diverge.
  local GROK_ARGS=(grok --output-format streaming-json --cwd "$WORKSPACE" --always-approve -m "$GROK_MODEL" --prompt-file "$pf")
  {
    echo "=== TOOL: grok ($reason) ==="
    echo "=== CMD: $(printf '%q ' "${GROK_ARGS[@]}") ==="
    printf '{"type":"system","subtype":"%s","tool":"grok","model":%s}\n' \
      "$([[ $GROK_ONLY -eq 1 ]] && echo selected || echo fallback)" "\"$GROK_MODEL\""
  } | tee -a "$LOG"
  "${GROK_ARGS[@]}" 2>&1 | tee -a "$LOG"
  rm -f "$pf"
}

if [[ $GROK_ONLY -eq 1 ]]; then
  echo "=== log: tail -f $LOG ===" | tee "$LOG"
  run_grok "primary — --grok"
  exit
fi

{
  echo "=== TOOL: cursor-agent (primary) ==="
  echo "=== CMD: $CURSOR_CMD ==="
  echo "=== log: tail -f $LOG ==="
} | tee "$LOG"

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 "FALLBACK — cursor-agent failed"
}
