#!/usr/bin/env bash
# Run the REAL cockpit locally against the REAL prod DB (READ-ONLY) for fast UI testing — no 9-min deploy.
#
# Why: testing cockpit UI changes against a 9-minute Argo rebuild is brutal. This port-forwards prod postgres
# and serves the real cockpit locally so you iterate in seconds, in a real browser, on real data.
#
# Notes:
#   * forwards to 15432, NOT 5432 (a local postgres usually owns 5432; the forward would fail "address in use").
#   * READ-ONLY: scripts/dev_cockpit_local.py constructs repos without .migrate(); no writes to prod.
#   * Ctrl-C tears down the port-forward.
#
# Usage:  ./scripts/dev-cockpit-local.sh    then open http://127.0.0.1:8801/paper/sim?book=bybit_4edge
set -euo pipefail

NS=${NS:-foxhunt}
LPORT=${LPORT:-15432}
DEV_PORT=${FXHNT_DEV_PORT:-8801}

PW=$(kubectl get secret db-credentials -n "$NS" -o jsonpath='{.data.password}' | base64 -d)
PW_ENC=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1], safe=''))" "$PW")

echo "port-forward svc/postgres -> 127.0.0.1:${LPORT} (ns=${NS})"
kubectl port-forward -n "$NS" svc/postgres "${LPORT}:5432" >/dev/null 2>&1 &
PF=$!
trap 'kill $PF 2>/dev/null || true' EXIT
sleep 4

export FXHNT_OPERATIONAL_DSN="postgresql+psycopg://foxhunt:${PW_ENC}@127.0.0.1:${LPORT}/fxhnt"
export FXHNT_DEV_PORT="${DEV_PORT}"
echo "serving READ-ONLY cockpit against PROD data on http://127.0.0.1:${DEV_PORT}"
# --extra web (uvicorn/fastapi/jinja2) + --extra pg (psycopg) — the cockpit needs both; a bare `uv run` on a
# fresh env fails ModuleNotFoundError: uvicorn / psycopg.
uv run --extra web --extra pg python3 scripts/dev_cockpit_local.py
