#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$ROOT/.tmp/autoshorts-readonly-smoke"
LOG="$TMP_DIR/gateway.log"
OVERVIEW="$TMP_DIR/overview.json"
MODULES="$TMP_DIR/modules.json"
PID=""
cleanup() {
  if [[ -n "${PID}" ]] && kill -0 "${PID}" >/dev/null 2>&1; then
    kill "$PID" >/dev/null 2>&1 || true
    wait "$PID" >/dev/null 2>&1 || true
  fi
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT
mkdir -p "$TMP_DIR/runtime"
touch "$TMP_DIR/runtime/review.review"
PORT="$(python3 - <<'PY'
import socket
s=socket.socket(); s.bind(('127.0.0.1',0)); print(s.getsockname()[1]); s.close()
PY
)"
MODE="${AUTOSHORTS_ADAPTER_MODE:-local_probe}"
BASE="${AUTOSHORTS_API_BASE_URL:-}"
if [[ "$MODE" == "live_readonly" ]]; then
  if [[ -z "$BASE" ]]; then
    echo "ERROR: AUTOSHORTS_API_BASE_URL is required for live_readonly smoke" >&2
    exit 2
  fi
  case "$BASE" in
    http://127.0.0.1:*|http://localhost:*) ;;
    *) echo "ERROR: live_readonly smoke requires AUTOSHORTS_API_BASE_URL on localhost/127.0.0.1" >&2; exit 2 ;;
  esac
fi
cd "$ROOT/apps/api-gateway"
AUTOSHORTS_ADAPTER_MODE="$MODE" \
AUTOSHORTS_RUNTIME_BASE="$TMP_DIR/runtime" \
AUTOSHORTS_API_BASE_URL="$BASE" \
JARVIS_GATEWAY_PORT="$PORT" \
PYTHONPATH=. \
python3 -m uvicorn jarvis_gateway.main:app --host 127.0.0.1 --port "$PORT" > "$LOG" 2>&1 &
PID="$!"
python3 - <<PY
import time, urllib.request
url='http://127.0.0.1:$PORT/api/healthz'
for _ in range(50):
    try:
        with urllib.request.urlopen(url, timeout=1) as r:
            if r.status == 200: raise SystemExit(0)
    except Exception:
        time.sleep(0.2)
raise SystemExit('gateway did not become ready')
PY
curl -fsS "http://127.0.0.1:$PORT/api/overview" -o "$OVERVIEW"
curl -fsS "http://127.0.0.1:$PORT/api/modules" -o "$MODULES"
python3 - <<PY
import json
from pathlib import Path
overview=json.loads(Path('$OVERVIEW').read_text())
modules=json.loads(Path('$MODULES').read_text())
text=json.dumps({'overview': overview, 'modules': modules}).lower()
module=next(m for m in overview['modules'] if m['module_id']=='autoshorts')
assert module['primary_action']['href']=='/autoshorts'
assert module['primary_action']['mode']=='link_only'
assert len(module['kpis']) <= 3
assert module['source_health']['source_type'] in {'mock','local_probe','http_api'}
assert module['source_health']['contract_version']=='autoshorts.safe_status.v1'
if '$MODE' == 'live_readonly':
    assert module['source_health']['source_type'] == 'http_api'
for forbidden in ['token','oauth','secret','/home/','.mp4','.mov','.wav','.mp3','.png','.jpg','.webp','.srt','.ass','upload_url','render_manifest','ffmpeg','prompt','script_text','voiceover','caption','description','traceback','stacktrace','post ','put ','patch ','delete ']:
    if forbidden in text:
        raise SystemExit(f'forbidden autoshorts smoke output: {forbidden}')
module_registry=next(m for m in modules if m['module_id']=='autoshorts')
assert module_registry['actions_enabled'] is False
print('autoshorts-readonly smoke PASS: overview/modules safe, no media/path/secret leaks')
PY
