#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$ROOT/.tmp/operator-handoff"
cleanup() { "$ROOT/scripts/stop-operator-handoff.sh" >/dev/null 2>&1 || true; }
trap cleanup EXIT INT TERM
"$ROOT/scripts/stop-operator-handoff.sh" >/dev/null 2>&1 || true
"$ROOT/scripts/start-operator-handoff.sh"
# shellcheck disable=SC1091
source "$TMP_DIR/handoff.env"
check_url() {
  local url="$1" 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 "$JARVIS_FRONTEND_URL/" "JARVIS Dashboard"
check_url "$JARVIS_API_URL/api/healthz" "JARVIS API"
check_url "$FINANCE_FRONTEND_URL/" "Finance Dashboard"
check_url "$AUTOSHORTS_FRONTEND_URL/" "AutoShorts Dashboard"
if [[ -n "${HEALTH_DASHBOARD_URL:-}" ]]; then check_url "$HEALTH_DASHBOARD_URL" "Health Dashboard"; fi
for route in /finance /health /autoshorts /approvals /reports /settings; do check_url "$JARVIS_FRONTEND_URL$route" "JARVIS route $route"; done
python3 - "$JARVIS_API_URL" <<'PY'
from urllib.request import urlopen
import json, re, sys
api=sys.argv[1]
combined={}
for path in ['/api/demo-info','/api/overview','/api/modules']:
    with urlopen(api+path, timeout=5) as r: combined[path]=json.load(r)
demo=combined['/api/demo-info']
if demo.get('actions_enabled') is not False: raise SystemExit('actions_enabled is not false')
links=demo.get('legacy_links', {})
if links.get('finance')!='configured': raise SystemExit('finance legacy link not configured')
if links.get('autoshorts')!='configured': raise SystemExit('autoshorts legacy link not configured')
if links.get('health') not in {'configured_protected','locked_by_policy','not_configured','blocked'}: raise SystemExit('health link status invalid')
text=json.dumps(combined, sort_keys=True)
forbidden=[r'/home/', r'\.env', r'\.tmp', r'token', r'oauth', r'secret', r'password', r'\.mp4', r'\.png', r'\.jpg', r'finance\.sqlite', r'health.*\.db', r'traceback']
hits=[p for p in forbidden if re.search(p, text, re.I)]
if hits: raise SystemExit('forbidden API output patterns: '+', '.join(hits))
modules={module.get('module_id'): module for module in combined['/api/overview'].get('modules', [])}
for module_id, label in [('finance','Finance Dashboard öffnen'),('autoshorts','AutoShorts Dashboard öffnen')]:
    labels={link.get('label') for link in modules.get(module_id, {}).get('links', [])}
    if label not in labels: raise SystemExit(f'missing {module_id} dashboard link')
health=modules.get('health', {})
health_labels={link.get('label') for link in health.get('links', [])}
if not ({'Health Dashboard öffnen', 'Health Risk Cockpit öffnen'} & health_labels): raise SystemExit('missing health risk/handoff link')
health_kpis={kpi.get('key'): kpi.get('value') for kpi in health.get('kpis', [])}
if set(health_kpis) != {'overall_health_risk','vascular_risk','data_freshness'}: raise SystemExit('health overview is not risk cockpit KPI set')
if 'backup_freshness' in health_kpis or 'pipeline_status' in health_kpis: raise SystemExit('health overview still exposes technical backup/pipeline as main KPI')
print('OK: handoff API link status safe and configured')
PY
HTML="$(curl -fsS --max-time 5 "$JARVIS_FRONTEND_URL/")"
if printf '%s' "$HTML" | grep -Eiq '<iframe|token|oauth|secret|/home/'; then
  echo "FAIL: forbidden frontend shell pattern" >&2
  exit 1
fi
if grep -R "Open module" "$ROOT/apps/dashboard/src/pages" "$ROOT/apps/dashboard/src/components/module" >/dev/null; then
  echo "FAIL: redundant Open module text remains in operator UI" >&2
  exit 1
fi
if grep -R "<iframe" "$ROOT/apps/dashboard/src" >/dev/null; then
  echo "FAIL: iframe found in dashboard source" >&2
  exit 1
fi
if grep -R -E ">[[:space:]]*(Approve|Reject|Upload|Render|Publish|Start|Delete)[[:space:]]*<" "$ROOT/apps/dashboard/src/pages" "$ROOT/apps/dashboard/src/components" >/dev/null; then
  echo "FAIL: active action button text found in dashboard source" >&2
  exit 1
fi
for expected in "Health Risk Cockpit" "Behçet-Aktivität" "Augen" "Gefässe/Thrombose" "Entzündung/Labortrend" "Medikamenten-Sicherheit" "Kontrollen & Datenstatus" "Health Dashboard" "Finance Dashboard öffnen" "AutoShorts Dashboard öffnen" "Zusammenfassung öffnen" "Fachdashboard öffnen"; do
  if ! grep -R "$expected" "$ROOT/apps/dashboard/src/pages" "$ROOT/apps/dashboard/src/components" >/dev/null; then
    echo "FAIL: expected operator UX text missing: $expected" >&2
    exit 1
  fi
done
echo "operator-handoff smoke PASS: JARVIS/Finance/AutoShorts reachable, Health Risk Cockpit verified, protected Health dashboard handoff checked"
