#!/usr/bin/env bash
# Full debug capture for skill-game research (Draw Poker, Blackjack, etc.).
#
# pos2 Slave + pos3 Master: VERBOSE=1, CHANNEL=both, fixture-timing/data/, no prod.
#
# Usage:
#   cd ~/EtherGold/sync
#   FIXTURE_POS=2 bash switch_bench_skill_research.sh
#   FIXTURE_POS=3 bash switch_bench_skill_research.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ethergold_paths.sh
source "${SCRIPT_DIR}/ethergold_paths.sh"
export FIXTURE_MODE=debug
# shellcheck source=source_fixture_env.sh
source "${SCRIPT_DIR}/source_fixture_env.sh"
# shellcheck source=resolve_bench_timing.sh
source "${SCRIPT_DIR}/resolve_bench_timing.sh"

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

POS="${FIXTURE_POS:-}"
if [[ ! "${POS}" =~ ^(2|3)$ ]]; then
  echo "FATAL: skill-research profile is for pos2 (Slave) or pos3 (Master) only" >&2
  exit 1
fi

TIMING="$(resolve_bench_timing_root)"

FIXTURE_POS="${POS}" bash "${SCRIPT_DIR}/disable_bench_prod.sh"
bash "${SCRIPT_DIR}/enable_lab_keno_jpot_env.sh" --off 2>/dev/null || true

for pattern in fixture_supervisor fixture_link_watch pog422_fixture_bridge pog422_fixture_listen; do
  pkill -TERM -f "${pattern}" 2>/dev/null || true
done
sleep 1
for pattern in fixture_supervisor fixture_link_watch pog422_fixture_bridge pog422_fixture_listen; do
  pkill -KILL -f "${pattern}" 2>/dev/null || true
done
rm -f "${TIMING}/.bridge.pid"

export FIXTURE_MODE=debug
export FIXTURE_PROD=0
export VERBOSE=1
export CHANNEL=both
export CLEAR_CAPTURE="${CLEAR_CAPTURE:-1}"
export FIXTURE_LAB_KENO_JPOT_SYNTH=0
export POG422_UARTD=0
export POG422_UARTD_CAPTURE=0
export POG422_UARTD_INJECT=0

echo "=== skill-research debug bridge pos=${POS} CHANNEL=${CHANNEL} VERBOSE=${VERBOSE} ==="
echo "  capture -> ${TIMING}/data/  logs -> ${TIMING}/logs/"
echo "  Play Draw Poker on pos2 Slave; pos3 witnesses Master egress (0x59, 0x52, 0x5A)."

cd "${TIMING}"
FIXTURE_POS="${POS}" bash start_bridge_background.sh
