#!/usr/bin/env bash
# Run the live 3D broadcast of a real prod instance + the headless YouTube gateway, on the gateway VM.
# The Cloud SQL proxy must already be listening on 127.0.0.1:5432 (see GATEWAY_VM.md §4).
#
# Env:
#   VR_INSTANCE / VR_COURSE   required — the instance/course ids (e.g. ulf:car / ulf:car)
#   YOUTUBE_STREAM_KEY        required unless --dry-run
#   TITLE                     optional broadcast title
#   SCENE_PARAMS              optional extra scene query params, e.g.
#                             'craft=car&backcam=ulf:boat:1&instance=ulf:car&readBase=https://apps.viewregatta.com'
#   VR_DATABASE_URL           optional — defaults to the Secret Manager password via the local proxy
#
# Extra args are passed through to gcp_gateway.py (e.g. --dry-run, --bitrate 4500).
set -euo pipefail

: "${VR_INSTANCE:?set VR_INSTANCE (e.g. ulf:car)}"
: "${VR_COURSE:?set VR_COURSE (e.g. ulf:car)}"

REPO="$(cd "$(dirname "$0")/../../.." && pwd)"
PY="$REPO/.venv/bin/python"

# DSN through the local cloud-sql-proxy; credentials from the canonical Secret Manager secret.
if [ -z "${VR_DATABASE_URL:-}" ]; then
    secret="$(gcloud secrets versions access latest --secret=VR_DATABASE_URL --project apps-viewregatta)"
    creds="$(printf '%s' "$secret" | sed -E 's#.*://([^@]+)@.*#\1#')"
    export VR_DATABASE_URL="postgresql://${creds}@127.0.0.1:5432/vr_v3"
fi

title_args=()
[ -n "${TITLE:-}" ] && title_args=(--title "$TITLE")

# --neural-tts is not optional here. The browser voice is the FALLBACK (speech-dispatcher + espeak-ng,
# installed by setup_gateway_vm.sh); the neural clips are what carry the commentary, and without the
# flag the producer renders none, so every line falls to a voice that may not exist. Both halves are
# now provisioned, and neither used to be: the stream went out silent (Ulf 2026-08-11).
"$PY" "$REPO/v3/broadcast/live/serve_v3_live.py" --live \
    --instance "$VR_INSTANCE" --course "$VR_COURSE" "${title_args[@]}" --wind --neural-tts &
serve_pid=$!
trap 'kill "$serve_pid" 2>/dev/null || true' EXIT
sleep 8   # let the scene server come up before Chrome loads it

# `trustedAutoplayAudio=1` is the page's own gate, and it is SEPARATE from the picture's. A `feed=live`
# page holds its commentary scheduler shut until a gesture unlocks the voice; this gateway supplies
# one blind xdotool click on a timer, which a slow cold start silently outruns. Chromium here is
# launched with `--autoplay-policy=no-user-gesture-required` (`gcp_gateway.chromium_cmd`), which is
# exactly the precondition this parameter declares — so the voice no longer depends on a click landing.
scene="http://localhost:8765/core/web/index.html?feed=live&trustedAutoplayAudio=1${SCENE_PARAMS:+&${SCENE_PARAMS}}"
"$PY" "$REPO/v3/broadcast/live/gcp_gateway.py" --url "$scene" --chromium google-chrome "$@"
