#!/usr/bin/env bash
# ca-run.sh — build prompt from plan JSONL then dispatch cursor-agent (composer-2.5) in one shot.
# audience: AI glue agents (haiku). One command replaces the two-step promptbuilder+ca-implement pair.
# CONTRACT:
#   ca-run.sh --plan JSONL --task TASK_ID --worktree WT --task-slug SLUG
#             [--timeout S] [--fix-findings JSON]
#   STDOUT: exactly one JSON line from ca-implement.sh
#     {"ok":true|false,"baseSha":"...","headSha":"...","files":[...],"commitCount":N,"detail":"..."}
#   exit 0 always (verdict in JSON). exit 2 on caller usage error.
set -uo pipefail

LIB="$(dirname "${BASH_SOURCE[0]}")"
usage() { printf '{"ok":false,"baseSha":"","headSha":"","files":[],"commitCount":0,"detail":"ca-run usage: %s"}\n' "$*" >&2; exit 2; }

PLAN=""; TASK_ID=""; WORKTREE=""; TASK_SLUG=""
TIMEOUT="3480"; FIX_FINDINGS=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --plan)          PLAN="${2:-}";         shift 2 ;;
    --task)          TASK_ID="${2:-}";      shift 2 ;;
    --worktree)      WORKTREE="${2:-}";     shift 2 ;;
    --task-slug)     TASK_SLUG="${2:-}";    shift 2 ;;
    --timeout)       TIMEOUT="${2:-}";      shift 2 ;;
    --fix-findings)  FIX_FINDINGS="${2:-}"; shift 2 ;;
    --model|--effort) shift 2 ;;   # accepted, ignored — always composer-2.5, no effort tiers
    *) usage "unknown arg: $1" ;;
  esac
done

[[ -n "$PLAN" && -f "$PLAN" ]]         || usage "--plan missing or not a file: ${PLAN:-<empty>}"
[[ -n "$TASK_ID" ]]                    || usage "--task required"
[[ -n "$WORKTREE" && -d "$WORKTREE" ]] || usage "--worktree missing or not a dir: ${WORKTREE:-<empty>}"
[[ -n "$TASK_SLUG" ]]                  || usage "--task-slug required"

PROMPT_FILE="$(dirname "$WORKTREE")/car-${TASK_SLUG}-$$.prompt.txt"   # never /tmp — $WORKTREE lives at <tmp-root>/wt-*, its parent IS the resolved tmp root

PB_ARGS=(--plan "$PLAN" --task "$TASK_ID" --worktree "$WORKTREE" --out "$PROMPT_FILE")
[[ -n "$FIX_FINDINGS" ]] && PB_ARGS+=(--fix-findings "$FIX_FINDINGS")

bash "$LIB/promptbuilder.sh" "${PB_ARGS[@]}" >/dev/null \
  || { printf '{"ok":false,"baseSha":"","headSha":"","files":[],"commitCount":0,"detail":"promptbuilder failed for task %s"}\n' "$TASK_ID"; exit 0; }

exec bash "$LIB/ca-implement.sh" \
  --worktree "$WORKTREE" \
  --task-slug "$TASK_SLUG" \
  --prompt-file "$PROMPT_FILE" \
  --timeout "$TIMEOUT"
