#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
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"; }

mkfixture() {
  local dir
  dir="$(mktemp -d "/tmp/codex-session-XXXX")"
  mkdir -p "$dir/wrappers/lib" "$dir/bin" "$dir/workflows/lib"
  cp "$ROOT/wrappers/codex.sh" "$dir/wrappers/codex.sh"
  cp "$ROOT/wrappers/lib/verdict-status.py" "$ROOT/wrappers/lib/finalize.sh" "$ROOT/wrappers/lib/spend-cap.sh" "$dir/wrappers/lib/"
  chmod +x "$dir/wrappers/codex.sh"
  : > "$dir/workflows/lib/CODEX.env"
  printf '%s\n' "$dir"
}

write_mock_codex() {
  local dir="$1"
  cat > "$dir/bin/codex" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

log_file="${MOCK_LOG_FILE:?}"

# Brace-bearing defaults live in variables: ${VAR:-{...}} ends at the first unescaped }.
DEFAULT_MODELS_OUTPUT='{"data":[]}'
DEFAULT_RUN_OUTPUT='{"type":"item.completed","item":{"content":[{"type":"output_text","text":"{\"clean\":true,\"findings\":[]}"}]}}'

printf '%s\n' "$*" >> "$log_file"

if [[ "${1:-}" == "--version" ]]; then
  printf '%s\n' "${MOCK_VERSION_OUTPUT:-codex 0.0.0}"
  exit "${MOCK_VERSION_EXIT_CODE:-0}"
fi

if [[ "${1:-}" == "models" ]]; then
  printf '%s\n' "${MOCK_MODELS_OUTPUT:-$DEFAULT_MODELS_OUTPUT}"
  exit "${MOCK_MODELS_EXIT_CODE:-0}"
fi

printf '%s\n' "${MOCK_RUN_OUTPUT:-$DEFAULT_RUN_OUTPUT}"
exit "${MOCK_RUN_EXIT_CODE:-0}"
EOF
  chmod +x "$dir/bin/codex"
}

run_dispatch_case() {
  local dir out rc log_file args status_line
  dir="$(mkfixture)"
  write_mock_codex "$dir"
  log_file="$dir/invocations.log"
  : > "$log_file"

  if out=$(
    PATH="$dir/bin:$PATH" \
    MOCK_LOG_FILE="$log_file" \
    MOCK_RUN_OUTPUT=$'{"type":"thread.started","thread_id":"thread-first"}\n{"type":"response.output_text.delta","delta":"ignore me"}\n{"type":"item.completed","item":{"type":"message","content":[{"type":"output_text","text":"{\\"clean\\":false,\\"findings\\":[{\\"file\\":\\"src/a.ts\\",\\"issue\\":\\"bad\\",\\"severity\\":\\"high\\"}],\\"steer\\":\\"forbidden\\",\\"kill\\":\\"allowed\\"}"}]}}' \
    _CODEX_ENGINE_BIN="$dir/bin/codex" \
    HOME="$dir/home" \
    HARNESS_SEAT_CONTAINER=1 \
    "$dir/wrappers/codex.sh" \
      --workspace "$dir" \
      --trust "review this" \
      --task-slug "task-1" \
      --model "gpt-5.5-high" \
      --timeout 30 \
      --permission-mode safe 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  args="$(grep 'exec .*--json' "$log_file" | tail -n 1 || true)"
  status_line="$(printf '%s\n' "$out" | tail -n 1)"

  if [[ "$rc" -eq 0 ]]; then
    ok "dispatch exits zero"
  else
    bad "dispatch exits zero" "rc=$rc out=${out:-<empty>}"
  fi

  if [[ "$args" == *"--json"* ]]; then
    ok "dispatch enables codex json event mode"
  else
    bad "dispatch enables codex json event mode" "$(cat "$log_file")"
  fi

  if [[ "$args" == *"--model gpt-5.5"* ]] && [[ "$args" == *"-c model_reasoning_effort=high"* ]]; then
    ok "dispatch splits model and effort flags"
  else
    bad "dispatch splits model and effort flags" "$args"
  fi

  if printf '%s\n' "$status_line" | grep -Fq '"thread_id":"thread-first"'; then
    ok "dispatch reports captured thread id"
  else
    bad "dispatch reports captured thread id" "${status_line:-<empty>}"
  fi

  if printf '%s\n' "$status_line" | grep -Fq '"steer":"forbidden"' && printf '%s\n' "$status_line" | grep -Fq '"kill":"allowed"'; then
    ok "dispatch reparses verdict from item.completed"
  else
    bad "dispatch reparses verdict from item.completed" "${status_line:-<empty>}"
  fi

  rm -rf "$dir"
}

run_resume_case() {
  local dir out rc log_file args status_line
  dir="$(mkfixture)"
  write_mock_codex "$dir"
  log_file="$dir/invocations.log"
  : > "$log_file"

  if out=$(
    PATH="$dir/bin:$PATH" \
    MOCK_LOG_FILE="$log_file" \
    MOCK_RUN_OUTPUT='{"type":"item.completed","item":{"content":[{"type":"output_text","text":"{\"clean\":true,\"findings\":[]}"}]}}' \
    _CODEX_ENGINE_BIN="$dir/bin/codex" \
    HOME="$dir/home" \
    HARNESS_SEAT_CONTAINER=1 \
    "$dir/wrappers/codex.sh" \
      --workspace "$dir" \
      --trust "resume this" \
      --task-slug "task-2" \
      --model "gpt-5.5-high" \
      --thread-id "thread-existing-9" \
      --timeout 30 \
      --permission-mode safe 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  args="$(grep 'exec .*--json' "$log_file" | tail -n 1 || true)"
  status_line="$(printf '%s\n' "$out" | tail -n 1)"

  if [[ "$rc" -eq 0 ]]; then
    ok "resume dispatch exits zero"
  else
    bad "resume dispatch exits zero" "rc=$rc out=${out:-<empty>}"
  fi

  if [[ "$args" == *"--thread-id thread-existing-9"* ]]; then
    ok "resume dispatch forwards explicit thread id"
  else
    bad "resume dispatch forwards explicit thread id" "$args"
  fi

  if printf '%s\n' "$status_line" | grep -Fq '"thread_id":"thread-existing-9"'; then
    ok "resume dispatch preserves explicit thread id"
  else
    bad "resume dispatch preserves explicit thread id" "${status_line:-<empty>}"
  fi

  rm -rf "$dir"
}

run_health_case() {
  local dir out rc log_file
  dir="$(mkfixture)"
  write_mock_codex "$dir"
  log_file="$dir/invocations.log"
  : > "$log_file"

  if out=$(
    PATH="$dir/bin:$PATH" \
    MOCK_LOG_FILE="$log_file" \
    MOCK_VERSION_OUTPUT='codex 1.2.3' \
    _CODEX_ENGINE_BIN="$dir/bin/codex" \
    HOME="$dir/home" \
    HARNESS_SEAT_CONTAINER=1 \
    "$dir/wrappers/codex.sh" --health 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  if [[ "$rc" -eq 0 ]] && [[ "$out" == *'"version":"codex 1.2.3"'* ]]; then
    ok "health mode returns codex version json"
  else
    bad "health mode returns codex version json" "rc=$rc out=${out:-<empty>}"
  fi

  if grep -Fxq -- '--version' "$log_file"; then
    ok "health mode calls codex version"
  else
    bad "health mode calls codex version" "$(cat "$log_file")"
  fi

  rm -rf "$dir"
}

run_list_models_case() {
  local dir out rc log_file
  dir="$(mkfixture)"
  write_mock_codex "$dir"
  log_file="$dir/invocations.log"
  : > "$log_file"

  if out=$(
    PATH="$dir/bin:$PATH" \
    MOCK_LOG_FILE="$log_file" \
    MOCK_MODELS_OUTPUT='{"data":[{"id":"gpt-5.5"},{"id":"gpt-5.5-mini"}]}' \
    _CODEX_ENGINE_BIN="$dir/bin/codex" \
    HOME="$dir/home" \
    HARNESS_SEAT_CONTAINER=1 \
    "$dir/wrappers/codex.sh" --list-models 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  if [[ "$rc" -eq 0 ]] && [[ "$out" == *'"id":"gpt-5.5-mini"'* ]]; then
    ok "list-models mode proxies model listing"
  else
    bad "list-models mode proxies model listing" "rc=$rc out=${out:-<empty>}"
  fi

  if grep -Fxq 'models --json' "$log_file"; then
    ok "list-models mode calls codex models json"
  else
    bad "list-models mode calls codex models json" "$(cat "$log_file")"
  fi

  rm -rf "$dir"
}

echo "codex session:"
run_dispatch_case
run_resume_case
run_health_case
run_list_models_case
echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
