#!/usr/bin/env bash
# smoke-test.sh — verify the hub MIXES live + phone + SDR sources into ONE stream.
# No hardware needed: generates simulated phone (Opus/webm) and SDR (PCM/wav) inputs.
# PASS = the full "everything -> one stream" path works.
set -uo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
PORT=8199

# 1) simulate a phone capture (Opus in webm)
ffmpeg -hide_banner -y -f lavfi -i "sine=frequency=220:duration=6" -c:a libopus "$TMP/phone.webm" >/dev/null 2>&1
# 2) simulate an SDR analog-mic capture (PCM wav)
ffmpeg -hide_banner -y -f lavfi -i "sine=frequency=880:duration=6" -c:a pcm_s16le "$TMP/sdr.wav" >/dev/null 2>&1

# 3) MIX: live tone + phone + SDR into ONE live stream
python3 "$DIR/hub.py" stream test "$TMP/phone.webm" "$TMP/sdr.wav" --port $PORT > "$TMP/hub.log" 2>&1 &
HUB=$!
sleep 2
curl -s --max-time 3 "http://127.0.0.1:$PORT/stream" -o "$TMP/out.mp3" || true
kill $HUB 2>/dev/null || true
sleep 1

SIZE=$(wc -c < "$TMP/out.mp3" 2>/dev/null | tr -d ' ')
EDGES=$(grep -o -e '-> amix' "$TMP/hub.log" 2>/dev/null | wc -l | tr -d ' ' || true)
EDGES=$(echo "${EDGES:-0}" | tr -d ' ')

if [ "${SIZE:-0}" -gt 1000 ] && file "$TMP/out.mp3" 2>/dev/null | grep -q 'MPEG'; then
  echo "PASS: one valid MP3 stream from ${EDGES} mixed inputs (${SIZE} bytes)"
  exit 0
else
  echo "FAIL: stream invalid (${SIZE:-0} bytes, ${EDGES} amix edges)"
  echo "--- hub log tail ---"; tail -8 "$TMP/hub.log" 2>/dev/null
  exit 1
fi
