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

# Three.js / 3D work ONLY. Pinned to Grok 4.5 via cursor-agent.
# Sibling of ca.sh (composer-2.5). Never merge the two: ca.sh stays composer-only.

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

MODEL="cursor-grok-4.5-high"
# Fail closed: an unknown id makes cursor-agent silently fall through to the interactive default.
if ! cursor-agent --list-models 2>/dev/null | grep -qE "^${MODEL} - "; then
  echo "grok.sh: '${MODEL}' not offered by this account — see 'cursor-agent --list-models'" >&2
  exit 2
fi

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

CURSOR_ARGS=(cursor-agent --model "$MODEL" --print --output-format stream-json --stream-partial-output --workspace "$WORKSPACE" --trust "$PROMPT")
CURSOR_CMD=$(printf '%q ' "${CURSOR_ARGS[@]}")
{
  echo "=== TOOL: cursor-agent (grok 4.5) ==="
  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"
