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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="$(mktemp -d)"
HOME_DIR="$WORK/home"
WORKSPACE="$WORK/workspace"
FAKE_CDX="$WORK/fake-cdx"
OUTPUT="$WORK/wrapper.out"
FALLBACK_OUTPUT="$WORK/fallback.out"
SIDECAR="$WORK/sidecar.log"
FALLBACK_SIDECAR="$WORK/fallback-sidecar.log"
STATE="$WORK/state"
FALLBACK_STATE="$WORK/fallback-state"
ENV_FILE="$WORK/empty.env"
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"; }

cleanup() {
  local proc cmd
  for proc in /proc/[0-9]*; do
    [[ -r "$proc/cmdline" ]] || continue
    cmd="$(tr '\0' ' ' <"$proc/cmdline" 2>/dev/null || true)"
    if [[ "$cmd" == *"$SIDECAR"* || "$cmd" == *"$FALLBACK_SIDECAR"* ]]; then
      kill "${proc##*/}" 2>/dev/null || true
    fi
  done
  rm -rf "$WORK"
}
trap cleanup EXIT

mkdir -p "$HOME_DIR/.npm-global/bin" "$HOME_DIR/.claude/bin" "$WORKSPACE"

# HOME is redirected here, so the wrapper looks for its dispatch guard inside this fixture.
printf '#!/usr/bin/env bash\nexit 0\n' >"$HOME_DIR/.claude/bin/local-dispatch-guard"
chmod +x "$HOME_DIR/.claude/bin/local-dispatch-guard"
: >"$ENV_FILE"

cat >"$HOME_DIR/.npm-global/bin/ft" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
[[ "${1:-}" == tail ]] || exit 2
shift
exec tail "$@"
EOF
chmod +x "$HOME_DIR/.npm-global/bin/ft"

cat >"$FAKE_CDX" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

sidecar="${FAKE_SIDECAR:?}"
state_file="${FAKE_STATE_FILE:?}"
printf 'running\n' >"$state_file"

if [[ "${FAKE_MODE:-path}" == path ]]; then
  : >"$sidecar"
  printf '%s\n' "$sidecar"
  for index in $(seq 1 12); do
    printf 'sidecar-live-%s\n' "$index" >>"$sidecar"
    sleep 0.2
  done
  printf '%s\n' '{"usage":{"input_tokens":123,"output_tokens":45,"cached_input_tokens":7,"cost_usd":0.12}}' >>"$sidecar"
else
  printf 'fallback-progress\n'
  sleep 0.2
  printf 'fallback-finished\n'
fi

printf 'done\n' >"$state_file"
EOF
chmod +x "$FAKE_CDX"

run_wrapper() {
  local mode="$1" output="$2" sidecar_path="$3" state_file="$4"
  FAKE_MODE="$mode" \
    FAKE_SIDECAR="$sidecar_path" \
    FAKE_STATE_FILE="$state_file" \
    _CODEX_ENGINE_BIN="$FAKE_CDX" \
    _CODEX_ENV="$ENV_FILE" \
    HOME="$HOME_DIR" \
    "$ROOT/wrappers/codex.sh" \
      --workspace "$WORKSPACE" \
      --trust "run contract test" \
      --task-slug "aut-003" \
      --model "gpt-5.5-high" \
      --timeout 15 \
      --permission-mode safe >"$output" 2>&1
}

run_wrapper path "$OUTPUT" "$SIDECAR" "$STATE" &
wrapper_pid=$!
live_seen=0
for _ in $(seq 1 120); do
  state_value=""
  [[ -f "$STATE" ]] && state_value="$(<"$STATE")"
  if [[ "$state_value" == running ]] \
    && grep -Fq 'sidecar-live-1' "$OUTPUT" 2>/dev/null; then
    live_seen=1
    break
  fi
  kill -0 "$wrapper_pid" 2>/dev/null || break
  sleep 0.05
done

if [[ "$live_seen" -eq 1 ]]; then
  ok "sidecar content reaches stdout before child exit"
else
  bad "sidecar content reaches stdout before child exit" "$(tail -n 20 "$OUTPUT" 2>/dev/null || true)"
fi

wrapper_rc=0
wait "$wrapper_pid" || wrapper_rc=$?
if [[ "$wrapper_rc" -eq 0 ]]; then
  ok "sidecar dispatch exits zero"
else
  bad "sidecar dispatch exits zero" "rc=$wrapper_rc output=$(tail -n 20 "$OUTPUT" 2>/dev/null || true)"
fi

if grep -Fq '"kind":"started","model":"gpt-5.5-high"' "$OUTPUT" \
  && grep -Fq "\"workspace\":\"$WORKSPACE\"" "$OUTPUT" \
  && grep -Fq '"log":"' "$OUTPUT"; then
  ok "sidecar dispatch emits started event"
else
  bad "sidecar dispatch emits started event" "$(grep -F 'started' "$OUTPUT" 2>/dev/null || true)"
fi

usage_count="$(grep -c '"kind":"usage"' "$OUTPUT" 2>/dev/null || true)"
if [[ "$usage_count" -eq 1 ]] \
  && grep -Fq '"inputTokens":123' "$OUTPUT" \
  && grep -Fq '"outputTokens":45' "$OUTPUT" \
  && grep -Fq '"cachedTokens":7' "$OUTPUT" \
  && grep -Fq '"costUsd":0.12' "$OUTPUT"; then
  ok "sidecar dispatch emits one usage event with real numbers"
else
  bad "sidecar dispatch emits one usage event with real numbers" "usage_count=$usage_count output=$(tail -n 20 "$OUTPUT" 2>/dev/null || true)"
fi

leaked_tail=0
for _ in $(seq 1 20); do
  found=0
  for proc in /proc/[0-9]*; do
    [[ -r "$proc/cmdline" ]] || continue
    cmd="$(tr '\0' ' ' <"$proc/cmdline" 2>/dev/null || true)"
    if [[ "$cmd" == *"$SIDECAR"* && "$cmd" == *tail* ]]; then
      found=1
      break
    fi
  done
  if [[ "$found" -eq 0 ]]; then
    break
  fi
  leaked_tail=1
  sleep 0.05
done
if [[ "$leaked_tail" -eq 0 ]]; then
  ok "sidecar dispatch leaves no tail process"
else
  bad "sidecar dispatch leaves no tail process" "tail command still references $SIDECAR"
fi

run_wrapper fallback "$FALLBACK_OUTPUT" "$FALLBACK_SIDECAR" "$FALLBACK_STATE" &
fallback_pid=$!
fallback_rc=0
wait "$fallback_pid" || fallback_rc=$?
if [[ "$fallback_rc" -eq 0 ]]; then
  ok "printed-path fallback exits zero"
else
  bad "printed-path fallback exits zero" "rc=$fallback_rc output=$(tail -n 20 "$FALLBACK_OUTPUT" 2>/dev/null || true)"
fi

if grep -Fq '"kind":"usage","usage":{"unknown":true,"model":"gpt-5.5-high"}' "$FALLBACK_OUTPUT"; then
  ok "printed-path fallback emits unknown usage"
else
  bad "printed-path fallback emits unknown usage" "$(tail -n 20 "$FALLBACK_OUTPUT" 2>/dev/null || true)"
fi

echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
