#!/usr/bin/env bash
# cx-run.sh — build prompt from plan JSONL then dispatch codex in one shot.
# audience: AI glue agents (haiku). One command replaces the two-step promptbuilder+cx-implement pair.
# CONTRACT:
#   cx-run.sh --plan JSONL --task TASK_ID --worktree WT --task-slug SLUG
#             [--model M] [--effort E] [--timeout S] [--fix-findings JSON]
#   STDOUT: exactly one JSON line from cx-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":"cx-run usage: %s"}\n' "$*" >&2; exit 2; }

PLAN=""; TASK_ID=""; WORKTREE=""; TASK_SLUG=""
MODEL="gpt-5.4"; EFFORT="low"; 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 ;;
    --model)         MODEL="${2:-}";        shift 2 ;;
    --effort)        EFFORT="${2:-}";       shift 2 ;;
    --timeout)       TIMEOUT="${2:-}";      shift 2 ;;
    --fix-findings)  FIX_FINDINGS="${2:-}"; shift 2 ;;
    *) 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")/cxr-${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/cx-implement.sh" \
  --worktree "$WORKTREE" \
  --task-slug "$TASK_SLUG" \
  --prompt-file "$PROMPT_FILE" \
  --model "$MODEL" \
  --effort "$EFFORT" \
  --timeout "$TIMEOUT"
