#!/usr/bin/env bash
# cse-sweep/sweep.sh: fan out gpt-realtime-2.1-mini navigators over CSE platforms,
# score shards on gpt-realtime-2.1-mini, synthesize in one gpt-5.6-terra Responses call (low + priority).
# All model calls run on the shared always-on rtinfer endpoint served by
# cse-toold (discovered via ~/.cse-rtinfer/endpoint.json). That is the only path.
#
# Usage:
#   sweep.sh --topic "guardian life renewal risk" --accounts "Guardian"
#   sweep.sh --topic "expertise and workload" --emails "name@postman.com" --people "Name"
#   sweep.sh --topic "..." --tickets CSE-123,CSE-456 --since 2026-05-01
#   sweep.sh --topic "how should we structure CSE onboarding"   # topic scope (no accounts)
#   sweep.sh --mode strategy --audience "GTM leadership" --topic "..." --accounts A,B
#                                               # business-commentary final synthesis
#   sweep.sh --dry-run --topic "..."            # print scope= + branch manifest only
#   sweep.sh --smoke --topic "..." --accounts X # ONE branch end-to-end
#
# Env overrides:
#   CSE_SWEEP_MCP_URL              MCP plane URL (default http://127.0.0.1:9901/mcp/full)
#   CSE_RTINFER_URL               rtinfer endpoint base URL override (default discovery)
#   EXPLORE_RT_NAV_MODEL           navigator model (default gpt-realtime-2.1-mini)
#   EXPLORE_RT_SYNTH_MODEL         scorer model (default gpt-realtime-2.1-mini)
#   CSE_SWEEP_RESPONSES_MODEL      final synthesis model (default gpt-5.6-terra; low reasoning + priority)
#   CSE_RT_REASONING_STEER         navigator/scorer prompt steer (empty disables)
#   CSE_RT_NAV_REASONING_EFFORT    explicit navigator reasoning effort (unset omits)
#   CSE_RT_SCORER_REASONING_EFFORT scorer reasoning effort (default low)
#   EXPLORE_RT_NAV_COUNT           parallel navigators (default 8)
#   EXPLORE_SEARCH_DAEMON_POOL     warm pool size (default 4)
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NODE_BIN="${CSE_SWEEP_NODE:-node}"

case "${1:-}" in
  --help|-h)
    awk 'NR > 1 && /^set -euo pipefail$/ { exit } NR > 1 { print }' "$0" | sed 's/^# \{0,1\}//'
    exit 0
    ;;
esac

# Preflight: node 20+.
if ! command -v "$NODE_BIN" >/dev/null 2>&1; then
  echo "cse-sweep: node not found (need >= 20)" >&2
  exit 2
fi
NODE_MAJOR="$("$NODE_BIN" -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
if [ "$NODE_MAJOR" -lt 20 ]; then
  echo "cse-sweep: node >= 20 required (have $("$NODE_BIN" --version))" >&2
  exit 2
fi

# Validate scope before any network preflight so malformed or mixed invocations
# fail with the CLI contract instead of an unrelated daemon error.
"$NODE_BIN" "$SCRIPT_DIR/cse-sweep.mjs" --validate-only "$@"

# Preflight: MCP plane reachable (stateless POST initialize; GET returns 405).
MCP_URL="${CSE_SWEEP_MCP_URL:-http://127.0.0.1:9901/mcp/full}"
if ! curl -sf --connect-timeout 2 --max-time 8 -o /dev/null -X POST "$MCP_URL" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"cse-sweep-preflight","version":"0.1.0"}}}' 2>/dev/null; then
  echo "cse-sweep: MCP plane unreachable at $MCP_URL (is cse-toold running?)" >&2
  exit 2
fi

# Preflight: cse-toold rtinfer endpoint reachable + ready (server-side Codex
# auth). The orchestrator also fails loud with a run-dir marker, but probing
# here gives a clear early error. A dry run skips this (no model calls are made).
case " $* " in
  *" --dry-run "*) : ;;
  *)
    RT_ENDPOINT=""
    if [ -n "${CSE_RTINFER_URL:-}" ]; then
      RT_ENDPOINT="$CSE_RTINFER_URL"
    elif [ -f "$HOME/.cse-rtinfer/endpoint.json" ]; then
      RT_ENDPOINT="$(python3 -c "import json,sys; print(json.load(open('$HOME/.cse-rtinfer/endpoint.json'))['base_url'])" 2>/dev/null || true)"
    fi
    if [ -z "$RT_ENDPOINT" ]; then
      echo "cse-sweep: rtinfer endpoint not found (no \$CSE_RTINFER_URL and no ~/.cse-rtinfer/endpoint.json). Start cse-toold serve (infer listener + Codex auth)." >&2
      exit 2
    fi
    RT_HEALTH="$(curl -sf --connect-timeout 2 --max-time 8 "$RT_ENDPOINT/v1/infer/health" 2>/dev/null || true)"
    if ! printf '%s' "$RT_HEALTH" | grep -q '"ready":true'; then
      echo "cse-sweep: rtinfer endpoint not ready at $RT_ENDPOINT (is cse-toold serve running with Codex auth?)" >&2
      echo "cse-sweep: health=${RT_HEALTH:-<no response>}" >&2
      exit 2
    fi
    ;;
esac

exec "$NODE_BIN" "$SCRIPT_DIR/cse-sweep.mjs" "$@"
