#!/usr/bin/env bash
# na.sh — dispatch the FREE north coder in ONE fail-closed command. north's `ca.sh` twin.
# audience: AI coding agents first. Invoke by path; do NOT re-derive the env block or the claude -p line.
#
# WHY this exists: the north rig was inline prose in the skill — 6 `export`s + a bounded `claude -p` —
# retyped every dispatch. That is the prose-as-executable hazard (re-derivation = reformulation = the
# `ccr start &` hang class). One tested wrapper removes the re-derivation AND scopes the OpenRouter env
# to this subprocess, so it never pollutes the orchestrator's real-Anthropic shell.
#
# CONTRACT: na.sh --workspace <dir> --trust "<prompt>" --task-slug <slug> [--timeout <secs>]
#   - Ensures ccr is up via the TESTED ccr-up.sh (fail-closed: proxy down -> exit 3, NO dispatch).
#   - cd <workspace> (SHORT path — long absolute CWD triggers north's phantom-tree write bug).
#   - Runs north FOREGROUND, bounded by `timeout -k 5 <secs>` (default 360); stdin </dev/null (cannot hang).
#   - Logs raw json to ~/Projects/multideal/tmp/logs/<datetime>-<slug>.log (same dir as ca.sh, so the
#     cost-mining tooling finds both). First lines = TOOL + CMD header.
#   - Exit: north's own rc (0 ok; 124 = timeout/non-completion -> orchestrator retries ONCE or 429-waits).
#     2 = usage error; 3 = ccr down. north NEVER fixes/gates — that is cursor (ca.sh) + opus.
set -uo pipefail

WORKSPACE="" PROMPT="" TASK_SLUG="" TIMEOUT=360
while [[ $# -gt 0 ]]; do
  case "$1" in
    --workspace) WORKSPACE="${2:-}"; shift 2;;
    --trust)     PROMPT="${2:-}";    shift 2;;
    --task-slug) TASK_SLUG="${2:-}"; shift 2;;
    --timeout)   TIMEOUT="${2:-}";   shift 2;;
    *) shift;;
  esac
done

[[ -n "$WORKSPACE" && -d "$WORKSPACE" ]] || { echo '{"ok":false,"detail":"--workspace missing or not a dir"}' >&2; exit 2; }
[[ -n "$PROMPT" ]]    || { echo '{"ok":false,"detail":"--trust (prompt) required"}' >&2; exit 2; }
[[ -n "$TASK_SLUG" ]] || { echo '{"ok":false,"detail":"--task-slug required (log + retry hygiene)"}' >&2; exit 2; }

SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 1. ccr up — TESTED script, fail-closed. north has no point without the proxy.
CCR_JSON="$(bash "$HOME/.claude/workflows/lib/ccr-up.sh" north 2>/dev/null)"
case "$CCR_JSON" in
  *'"up":true'*) : ;;
  *) echo "{\"ok\":false,\"detail\":\"ccr not up: ${CCR_JSON}\"}" >&2; exit 3;;
esac

# 2. environment — sourced HERE, scoped to this subprocess (never leaks to the caller).
# shellcheck source=/dev/null
source "$SKILL_DIR/NORTH.env"

mkdir -p "$HOME/Projects/multideal/tmp/logs"
LOG="$HOME/Projects/multideal/tmp/logs/$(date +%Y-%m-%d-%H-%M-%S)-$TASK_SLUG.log"

# DRY: build the dispatch ONCE; header line and run line use the same array so they cannot diverge.
NORTH_ARGS=(timeout -k 5 "$TIMEOUT" claude -p "$PROMPT" --output-format json --dangerously-skip-permissions)
{
  echo "=== TOOL: north (cohere/north-mini-code:free) via ccr ==="
  echo "=== CMD: $(printf '%q ' "${NORTH_ARGS[@]}") ==="
  echo "=== workspace: $WORKSPACE  timeout: ${TIMEOUT}s  log: $LOG ==="
} | tee "$LOG"

# 3. dispatch FOREGROUND, in the (short) workspace, stdin closed. Never background, never pipe to a pager.
cd "$WORKSPACE" || { echo '{"ok":false,"detail":"cd workspace failed"}' >&2; exit 2; }
"${NORTH_ARGS[@]}" < /dev/null 2>&1 | tee -a "$LOG"
RC="${PIPESTATUS[0]}"
echo "=== north exit=$RC (124=timeout/non-completion: orchestrator retries once or waits out 429) ===" | tee -a "$LOG"
exit "$RC"
