#!/bin/bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
HOOK="$ROOT/configs/hook-speak.sh"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

assert_stdin_extracts() {
  local name="$1"
  local source="$2"
  local input="$3"
  local want="$4"
  local got

  got=$(printf "%s" "$input" | IVOX_HOOK_STATE_FILE="$TMPDIR/hook-test.last" IVOX_HOOK_PRINT_TEXT=1 bash "$HOOK" "$source")
  if [[ "$got" != "$want" ]]; then
    echo "hook fixture failed: $name" >&2
    echo "want: $want" >&2
    echo "got:  $got" >&2
    exit 1
  fi
}

assert_arg_extracts() {
  local name="$1"
  local source="$2"
  local input="$3"
  local want="$4"
  local got

  got=$(IVOX_HOOK_STATE_FILE="$TMPDIR/hook-test.last" IVOX_HOOK_PRINT_TEXT=1 bash "$HOOK" "$source" "$input")
  if [[ "$got" != "$want" ]]; then
    echo "hook fixture failed: $name" >&2
    echo "want: $want" >&2
    echo "got:  $got" >&2
    exit 1
  fi
}

assert_stdin_extracts "claude direct field" claude \
  '{"last_assistant_message":"Claude 直接字段"}' \
  "Claude 直接字段"

assert_stdin_extracts "codex stop stdin field" codex \
  '{"turn_id":"turn-456","last_assistant_message":"Codex Stop 字段"}' \
  "Codex Stop 字段"

assert_arg_extracts "codex ignores legacy kebab field" codex \
  '{"turn-id":"turn-123","last-assistant-message":"Codex 横杠字段"}' \
  ""

cat > "$TMPDIR/codex-events.jsonl" <<'JSONL'
{"type":"user.message","data":{"content":"检查声音"},"id":"codex-user","timestamp":"2026-05-18T00:00:00Z"}
{"type":"assistant.message","data":{"content":"Codex transcript 不应播"},"id":"codex-assistant","timestamp":"2026-05-18T00:00:01Z"}
JSONL

got=$(printf '{"turn_id":"codex-turn-1","transcript_path":"%s/codex-events.jsonl"}' "$TMPDIR" |
  IVOX_HOOK_STATE_FILE="$TMPDIR/hook-test.last" IVOX_HOOK_PRINT_TEXT=1 bash "$HOOK" codex)
if [[ "$got" != "" ]]; then
  echo "hook fixture failed: codex ignores transcript fallback" >&2
  echo "want: " >&2
  echo "got:  $got" >&2
  exit 1
fi

assert_cli_payload() {
  local name="$1"
  local command="$2"
  local input="$3"
  local want="$4"
  local got

  got=$(IVOX_CLI_PRINT_PAYLOAD=1 "$ROOT/scripts/$command" $input)
  if [[ "$got" != "$want" ]]; then
    echo "cli source fixture failed: $name" >&2
    echo "want: $want" >&2
    echo "got:  $got" >&2
    exit 1
  fi
}

assert_cli_payload "plain ivox keeps default source" ivox \
  "默认入口" \
  "默认入口"

assert_cli_payload "claude source via -s flag" ivox \
  "-s claude Claude 入口" \
  "{source:claude}Claude 入口"

assert_cli_payload "codex source via -s flag" ivox \
  "-s codex Codex 入口" \
  "{source:codex}Codex 入口"

assert_cli_payload "pi source via -s flag" ivox \
  "-s pi Pi 入口" \
  "{source:pi}Pi 入口"

echo "hook fixtures passed"
