#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$ROOT/.tmp/operator-demo"

cleanup() {
  "$ROOT/scripts/stop-operator-demo.sh" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM

"$ROOT/scripts/stop-operator-demo.sh" >/dev/null 2>&1 || true
"$ROOT/scripts/start-operator-demo.sh" demo_mock

# shellcheck disable=SC1091
source "$TMP_DIR/demo.env"

check_url() {
  local url="$1"
  local label="$2"
  if ! curl -fsS --max-time 5 "$url" >/dev/null; then
    echo "FAIL: $label not reachable: $url" >&2
    return 1
  fi
  echo "OK: $label reachable: $url"
}

check_url "$API_BASE/api/healthz" "API healthz"
check_url "$API_BASE/api/modules" "API modules"
check_url "$API_BASE/api/overview" "API overview"
check_url "$API_BASE/api/demo-info" "API demo-info"
for route in / /approvals /reports /settings /finance /health /autoshorts /system; do
  check_url "$FRONTEND_BASE$route" "Dashboard route $route"
done

python3 - "$API_BASE" <<'PY'
from urllib.request import urlopen
import json
import re
import sys
api = sys.argv[1]
paths = ['/api/healthz', '/api/modules', '/api/overview', '/api/demo-info']
combined = {}
for path in paths:
    with urlopen(api + path, timeout=5) as response:
        combined[path] = json.load(response)
text = json.dumps(combined, sort_keys=True)
forbidden = [
    r'/home/', r'\.env', r'\.tmp', r'node_modules', r'dist/',
    r'token', r'oauth', r'secret', r'password', r'refresh_token', r'access_token',
    r'\.mp4', r'\.mov', r'\.wav', r'\.mp3', r'\.png', r'\.jpg', r'\.webp', r'\.srt', r'\.ass',
    r'POST', r'PUT', r'PATCH', r'DELETE',
    r'traceback', r'stack trace', r'finance\.sqlite', r'health.*\.db',
]
hits = [pattern for pattern in forbidden if re.search(pattern, text, flags=re.IGNORECASE)]
if hits:
    raise SystemExit('forbidden API output patterns: ' + ', '.join(hits))
overview = combined['/api/overview']
modules = overview.get('modules', [])
module_ids = {item.get('module_id') for item in modules}
required = {'finance', 'health', 'autoshorts', 'system'}
if not required.issubset(module_ids):
    raise SystemExit(f'missing required modules: {sorted(required - module_ids)}')
if len(modules) > 4:
    raise SystemExit(f'too many modules: {len(modules)}')
for module in modules:
    if len(module.get('kpis', [])) > 3:
        raise SystemExit(f"too many KPIs for {module.get('module_id')}")
    action = module.get('primary_action')
    if action and action.get('mode') != 'link_only':
        raise SystemExit(f"primary action is not link_only for {module.get('module_id')}")
demo = combined['/api/demo-info']
if demo != {
    'mode': 'demo_mock',
    'actions_enabled': False,
    'modules': ['finance', 'health', 'autoshorts', 'system'],
    'runtime_access': 'disabled',
    'legacy_links': {'finance': 'not_configured', 'health': 'not_configured', 'autoshorts': 'not_configured'},
}:
    raise SystemExit('unexpected demo-info payload: ' + json.dumps(demo, sort_keys=True))
allowed_status = {'configured', 'not_configured', 'blocked'}
if set(demo['legacy_links'].values()) - allowed_status:
    raise SystemExit('unexpected legacy link status')
if any('http' in str(value) or '/' in str(value) for value in demo['legacy_links'].values()):
    raise SystemExit('demo-info leaked URL-like legacy link value')
print('OK: operator demo API output safe and contract-shaped')
PY

HTML="$(curl -fsS --max-time 5 "$FRONTEND_BASE/")"
if printf '%s' "$HTML" | grep -Eiq '<iframe|upload button|render button|publish button|approve button|token|oauth|secret|/home/'; then
  echo "FAIL: forbidden frontend shell pattern" >&2
  exit 1
fi

echo "operator-demo smoke PASS: dashboard routes reachable, modules safe, no secret/path/media leaks"
