#!/bin/bash
set -euo pipefail

REPO_ROOT="$(cd "${BASH_SOURCE[0]%/*}/../../../.." && pwd -P)"
ENTRY="$REPO_ROOT/modules/workstation/claude/bin/model-test-fixture"
PASS=0
FAIL=0
ok() { PASS=$((PASS + 1)); printf '  ok   %s\n' "$1"; }
bad() { FAIL=$((FAIL + 1)); printf '  FAIL %s\n     %s\n' "$1" "$2"; }

TMP="$(mktemp -d /tmp/model-test-fixture-XXXXXX)"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/hostile-home" "$TMP/hostile-bin"
: > "$TMP/launched.log"
for name in bash getent id opencode cdx claude python3 timeout; do
  printf '#!/bin/bash\nprintf "%%s\\n" "%s" >> "%s"\nexit 99\n' "$name" "$TMP/launched.log" > "$TMP/hostile-bin/$name"
  chmod +x "$TMP/hostile-bin/$name"
done

OVERRIDES=(
  _OPENCODE_ENGINE_BIN="$TMP/hostile-bin/opencode" _CODEX_ENGINE_BIN="$TMP/hostile-bin/cdx" _CODEX_ENV=INJECTED
  _NA_CLAUDE_BIN="$TMP/hostile-bin/claude" _NA_CCR_UP_BIN=INJECTED _NA_NORTH_ENV=INJECTED
  OPENCODE_CONFIG=INJECTED OPENCODE_CONFIG_DIR=INJECTED OPENCODE_CONFIG_CONTENT=INJECTED OPENCODE_MODEL=INJECTED
  CODEX_HOME=INJECTED OPENAI_BASE_URL=INJECTED OPENAI_API_BASE=INJECTED
  CLAUDE_CONFIG_DIR=INJECTED ANTHROPIC_BASE_URL=INJECTED ANTHROPIC_MODEL=INJECTED ANTHROPIC_SMALL_FAST_MODEL=INJECTED
  ANTHROPIC_DEFAULT_OPUS_MODEL=INJECTED ANTHROPIC_DEFAULT_SONNET_MODEL=INJECTED ANTHROPIC_DEFAULT_HAIKU_MODEL=INJECTED
  CLAUDE_CODE_USE_BEDROCK=1 CLAUDE_CODE_USE_VERTEX=1 ANTHROPIC_BEDROCK_BASE_URL=INJECTED ANTHROPIC_VERTEX_BASE_URL=INJECTED
  CCR_PORT=1 CCR_CMD=INJECTED CCR_UP_TIMEOUT=1 CCR_LOCK_WAIT=1 CCR_TMP_ROOT=INJECTED
)

run_fixture() {
  env "${OVERRIDES[@]}" HOME="$TMP/hostile-home" PATH="$TMP/hostile-bin" \
    /bin/bash "$ENTRY" "$@"
}

assert_inspection() {
  local backend="$1" expected_engine="$2" expected_model="$3" expected_args_json="$4" output rc=0
  output="$(run_fixture --purpose verification --backend "$backend" --workspace "$TMP" --trust test-prompt --task-slug fixture-test --inspect 2>&1)" || rc=$?
  if [[ $rc -ne 0 ]]; then
    bad "$backend inspection pins route" "rc=$rc output=$output"
    return
  fi
  if JSON="$output" EXPECTED_ENGINE="$expected_engine" EXPECTED_MODEL="$expected_model" EXPECTED_ARGS="$expected_args_json" /usr/bin/python3 - <<'PY'
import json
import os

data = json.loads(os.environ["JSON"])
assert data["ok"] is True
assert data["purpose"] == "verification"
assert data["engine"] == os.environ["EXPECTED_ENGINE"]
assert data["model"] == os.environ["EXPECTED_MODEL"]
assert data["engine_args"] == json.loads(os.environ["EXPECTED_ARGS"])
assert data["engine"].startswith("/")
assert "hostile" not in json.dumps(data)
PY
  then
    ok "$backend inspection pins route"
  else
    bad "$backend inspection pins route" "$output"
  fi
}

assert_rejects_without_launch() {
  local label="$1" expected_rc="$2" output rc=0; shift 2
  : > "$TMP/launched.log"
  output="$(run_fixture "$@" 2>&1)" || rc=$?
  if [[ $rc -eq "$expected_rc" && ! -s "$TMP/launched.log" ]]; then
    ok "$label rejects before model launch"
  else
    bad "$label rejects before model launch" "rc=$rc output=$output launched=$(<"$TMP/launched.log")"
  fi
}

printf 'model test fixture:\n'
help_out="$(/bin/bash "$ENTRY" --help)"
if [[ "$help_out" == usage:\ model-test-fixture\ --purpose\ verification* && "$help_out" == *'--inspect validates pinned executables'* ]]; then
  ok 'help names verification purpose and no-launch inspection'
else
  bad 'help names verification purpose and no-launch inspection' "$help_out"
fi

owner_home="$(/usr/bin/getent passwd "$(/usr/bin/id -u)" | /usr/bin/cut -d: -f6)"
assert_inspection opencode "$owner_home/.claude/bin/opencode" deepseek-v4-flash-free \
  "$(/usr/bin/python3 -c 'import json,sys; print(json.dumps(["run","--model","deepseek-v4-flash-free","--dangerously-skip-permissions","--dir",sys.argv[1],"test-prompt"]))' "$TMP")"
assert_inspection codex "$owner_home/.local/bin/cdx" gpt-5.3-codex-spark \
  "$(/usr/bin/python3 -c 'import json,sys; print(json.dumps(["exec","--json","-C",sys.argv[1],"--skip-git-repo-check","--model","gpt-5.3-codex-spark","-c","model_reasoning_effort=high","test-prompt"]))' "$TMP")"
codex_profile_json="$(run_fixture --purpose verification --backend codex --profile zync2 --workspace "$TMP" --trust test-prompt --task-slug fixture-test --inspect)"
if JSON="$codex_profile_json" /usr/bin/python3 - <<'PY'
import json
import os

data = json.loads(os.environ["JSON"])
assert data["model"] == "gpt-5.3-codex-spark"
assert data["engine_args"][0] == "--profile=zync2"
assert data["engine_args"][1] == "exec"
PY
then ok 'codex inspection pins explicit zync2 profile and model'; else bad 'codex inspection pins explicit zync2 profile and model' "$codex_profile_json"; fi
assert_inspection north "$owner_home/.claude/bin/claude" cohere/north-mini-code:free \
  '["-p","test-prompt","--output-format","json","--dangerously-skip-permissions"]'

north_json="$(run_fixture --purpose verification --backend north --workspace "$TMP" --trust test-prompt --task-slug fixture-test --inspect)"
if JSON="$north_json" OWNER_HOME="$owner_home" /usr/bin/python3 - <<'PY'
import json
import os

env = json.loads(os.environ["JSON"])["environment"]
assert env == {
    "CLAUDE_CONFIG_DIR": os.environ["OWNER_HOME"] + "/.claude-openrouter",
    "ANTHROPIC_BASE_URL": "http://127.0.0.1:3456",
    "ANTHROPIC_MODEL": "cohere/north-mini-code:free",
    "ANTHROPIC_SMALL_FAST_MODEL": "cohere/north-mini-code:free",
}
PY
then ok 'north inspection exposes exact deployed environment'; else bad 'north inspection exposes exact deployed environment' "$north_json"; fi

if [[ ! -s "$TMP/launched.log" ]]; then ok 'hostile PATH executables never launch'; else bad 'hostile PATH executables never launch' "$(<"$TMP/launched.log")"; fi
assert_rejects_without_launch 'missing purpose' 2 --backend opencode --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'wrong purpose' 2 --purpose implementation --backend opencode --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'caller model override' 2 --purpose verification --backend opencode --model other --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'invalid timeout' 2 --purpose verification --backend codex --workspace "$TMP" --trust test --task-slug fixture --timeout 0 --inspect
assert_rejects_without_launch 'profile on non-codex backend' 2 --purpose verification --backend opencode --profile zync2 --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'empty profile' 2 --purpose verification --backend codex --profile '' --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'unsafe profile selector' 2 --purpose verification --backend codex --profile '../other' --workspace "$TMP" --trust test --task-slug fixture --inspect
assert_rejects_without_launch 'unknown flag' 2 --purpose verification --backend north --workspace "$TMP" --trust test --task-slug fixture --fallback --inspect
assert_rejects_without_launch 'fixture rejects canonical North engine override' 2 --purpose verification --backend north --workspace "$TMP" --trust test --task-slug fixture --inspect --claude-bin "$TMP/hostile-bin/claude"

: > "$TMP/launched.log"
canonical_rc=0
canonical_out="$(HOME="$TMP/hostile-home" PATH="$TMP/hostile-bin" /bin/bash "$REPO_ROOT/modules/workstation/claude/skills/north-orchestrator/na.sh" --workspace "$TMP" --trust test --task-slug fixture --claude-bin "$TMP/hostile-bin/claude" --inspect 2>&1)" || canonical_rc=$?
if [[ $canonical_rc -eq 3 && ! -s "$TMP/launched.log" ]]; then
  ok 'canonical North rejects non-owner Claude executable'
else
  bad 'canonical North rejects non-owner Claude executable' "rc=$canonical_rc output=$canonical_out launched=$(<"$TMP/launched.log")"
fi

printf '\nPASS=%s FAIL=%s\n' "$PASS" "$FAIL"
[[ "$FAIL" -eq 0 ]]
