#!/usr/bin/env bash
set -euo pipefail
API="${API:-http://localhost:3000}"
PLATFORM="${PLATFORM:-matchlivetv}"

echo "== Login =="
LOGIN=$(curl -sf -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"email":"coach@matchlivetv.test","password":"password123"}')
TOKEN=$(echo "$LOGIN" | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
echo "OK token received"

AUTH="Authorization: Bearer $TOKEN"

echo "== Teams =="
TEAMS=$(curl -sf -H "$AUTH" "$API/api/v1/teams")
TEAM_ID=$(echo "$TEAMS" | python3 -c "import sys,json; print(json.load(sys.stdin)[0]['id'])")
echo "Team: $TEAM_ID"

echo "== Matches =="
MATCHES=$(curl -sf -H "$AUTH" "$API/api/v1/teams/$TEAM_ID/matches")
MATCH_ID=$(echo "$MATCHES" | python3 -c "import sys,json; print(json.load(sys.stdin)[0]['id'])")
echo "Match: $MATCH_ID"

echo "== Create session (platform=$PLATFORM) =="
SESSION=$(curl -sf -X POST -H "$AUTH" -H "Content-Type: application/json" \
  "$API/api/v1/matches/$MATCH_ID/sessions" \
  -d "{\"platform\":\"$PLATFORM\",\"privacy_status\":\"unlisted\",\"quality_preset\":\"720p_30_2.5mbps\"}")
SESSION_ID=$(echo "$SESSION" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
echo "Session: $SESSION_ID"

python3 -c "
import sys, json
s = json.loads('''$SESSION''')
assert s.get('platform') == '$PLATFORM', s
if '$PLATFORM' == 'matchlivetv':
    assert s.get('hls_playback_url'), 'missing hls_playback_url'
    assert s.get('watch_page_url'), 'missing watch_page_url'
    assert not s.get('youtube_broadcast_id'), s
print('Session fields OK')
"

echo "== Start session =="
curl -sf -X PATCH -H "$AUTH" "$API/api/v1/sessions/$SESSION_ID/start" > /dev/null
echo "Started"

echo "== Webhook disconnect =="
SECRET="${MEDIAMTX_WEBHOOK_SECRET:-mediamtx_webhook_dev_secret}"
BODY="{\"session_id\":\"$SESSION_ID\"}"
SIG=$(echo -n "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
curl -sf -X POST "$API/webhooks/mediamtx/disconnect" \
  -H "Content-Type: application/json" \
  -H "X-MediaMTX-Signature: $SIG" \
  -d "$BODY"
echo "Disconnect OK"

STATUS=$(curl -sf -H "$AUTH" "$API/api/v1/sessions/$SESSION_ID" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
echo "Status after disconnect: $STATUS (expected reconnecting)"

echo "== Webhook connect =="
curl -sf -X POST "$API/webhooks/mediamtx/connect" \
  -H "Content-Type: application/json" \
  -H "X-MediaMTX-Signature: $SIG" \
  -d "$BODY"
STATUS=$(curl -sf -H "$AUTH" "$API/api/v1/sessions/$SESSION_ID" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
echo "Status after reconnect: $STATUS (expected live)"

echo "== Validate publish token =="
curl -sf -X POST "$API/internal/validate_publish" \
  -d "session_id=$SESSION_ID&token=fake" | grep -q '"valid":false' && echo "Invalid token rejected OK"

echo "== All E2E API checks passed =="
