#!/usr/bin/env bash
# Smoke lab synth on this hop. Exit 0 only if this TID has wager+ack.
# Usage: bash _tmp_smoke_chain_synth.sh [wait_s] [tid]
set -euo pipefail
LOG=~/EtherGold/logs/lab_gameplay_pilot/bridge.log
SEC="${1:-14}"
TID="${2:-${LAB_GAMEPLAY_TID:-}}"
sleep "$SEC"
if [[ ! -f "$LOG" ]]; then
  echo "FAIL missing $LOG"
  exit 1
fi
# Match either events.jsonl-style JSON or bridge.log echo lines.
if [[ -n "$TID" ]]; then
  W=$(grep -cE "lab_gameplay_synth_wager.*\"tid\": \"$TID\"|lab_gameplay_synth_wager.*tid[=:] ?$TID" "$LOG" || true)
  A=$(grep -cE "lab_gameplay_synth_ack.*\"tid\": \"$TID\"|lab_gameplay_synth_ack.*tid[=:] ?$TID" "$LOG" || true)
  S=$(grep -cE "trunk_round_stale_abandon.*\"tid\": \"$TID\"" "$LOG" || true)
else
  W=$(grep -c lab_gameplay_synth_wager "$LOG" || true)
  A=$(grep -c lab_gameplay_synth_ack "$LOG" || true)
  S=$(grep -c trunk_round_stale_abandon "$LOG" || true)
fi
# Also count from events.jsonl (dev-light often mirrors there).
EV=~/EtherGold/dev/data/events.jsonl
if [[ -f "$EV" ]]; then
  if [[ -n "$TID" ]]; then
    W2=$(grep -cE "lab_gameplay_synth_wager.*\"tid\": \"$TID\"" "$EV" || true)
    A2=$(grep -cE "lab_gameplay_synth_ack.*\"tid\": \"$TID\"" "$EV" || true)
  else
    W2=$(grep -c lab_gameplay_synth_wager "$EV" || true)
    A2=$(grep -c lab_gameplay_synth_ack "$EV" || true)
  fi
  if [[ "$W2" -gt "$W" ]]; then W=$W2; fi
  if [[ "$A2" -gt "$A" ]]; then A=$A2; fi
fi
echo "smoke tid=${TID:-any} wager=$W ack=$A stale=$S"
grep -E "lab_gameplay_synth_wager|lab_gameplay_synth_ack|trunk_round_stale" "$LOG" | tail -16 || true
if [[ "$W" -lt 1 || "$A" -lt 1 ]]; then
  echo "FAIL need wager>=1 and ack>=1"
  exit 1
fi
# Own-TID stale flood only (ignore overheard bus noise from other hops).
if [[ "$S" -gt $((A + 2)) ]]; then
  echo "FAIL own-tid stale>>ack"
  exit 1
fi
echo "PASS"
exit 0
