#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [[ -z "${HEALTH_RUNTIME_BASE:-}" ]]; then
  echo "ERROR: HEALTH_RUNTIME_BASE is not set. Provide a local metadata-safe Health runtime directory." >&2
  exit 1
fi
python3 - <<'PY'
import os
from pathlib import Path
base=Path(os.environ['HEALTH_RUNTIME_BASE']).expanduser()
if not base.is_absolute():
    raise SystemExit('ERROR: HEALTH_RUNTIME_BASE must be an absolute local path')
if not base.exists() or not base.is_dir():
    raise SystemExit('ERROR: HEALTH_RUNTIME_BASE does not exist or is not a directory')
print('OK: HEALTH_RUNTIME_BASE exists as local directory; smoke will inspect metadata only')
PY
PORT="${JARVIS_SMOKE_GATEWAY_PORT:-18081}"
TMP_DIR="$ROOT/.tmp/health-local-probe-smoke"
mkdir -p "$TMP_DIR"
PID=""
cleanup(){ set +e; if [[ -n "$PID" ]] && kill -0 "$PID" 2>/dev/null; then kill "$PID" 2>/dev/null || true; wait "$PID" 2>/dev/null || true; fi; }
trap cleanup EXIT INT TERM
(
  cd "$ROOT/apps/api-gateway"
  HEALTH_ADAPTER_MODE=local_probe ALLOW_HEALTH_DETAIL_LINKS=0 JARVIS_DEMO_MODE=0 PYTHONPATH=. python3 -m uvicorn jarvis_gateway.main:app --host 127.0.0.1 --port "$PORT"
) >"$TMP_DIR/gateway.log" 2>&1 &
PID="$!"
python3 - "$PORT" <<'PY'
import json, sys, time
from urllib.request import urlopen
port=sys.argv[1]
base=f'http://127.0.0.1:{port}'
for _ in range(80):
    try:
        with urlopen(base+'/api/healthz', timeout=1) as r:
            if r.status == 200: break
    except Exception:
        time.sleep(0.25)
else:
    raise SystemExit('ERROR: Jarvis gateway did not start')
bad_terms=['diagnosis','diagnose','befund','labor','medication','medikament','arztbericht','report_text','ocr','extrahierte_inhalte','patient','symptom','yazio','apple_health','blood','crp','cholesterol','faktor','eliquis','colchicin','adalimumab','hyrimoz','pdf_text','drive_web_url','drive_file_id','local_original_path','health_data.db','/home/agent','traceback','token','secret','password','api_key','.pdf','.db','.sqlite']
modules_data=None
overview_data=None
for path in ['/api/modules','/api/overview']:
    with urlopen(base+path, timeout=5) as r:
        if r.status != 200: raise SystemExit(f'ERROR: {path} returned {r.status}')
        data=json.loads(r.read().decode())
        text=json.dumps(data).lower()
        for bad in bad_terms:
            if bad in text: raise SystemExit(f'ERROR: forbidden health string leaked: {bad}')
        if path == '/api/modules': modules_data=data
        if path == '/api/overview': overview_data=data
health_registry=[m for m in modules_data if m.get('module_id')=='health']
if not health_registry: raise SystemExit('ERROR: missing health registry entry')
if health_registry[0].get('source_type') != 'local_probe': raise SystemExit('ERROR: health registry source_type is not local_probe')
health=[m for m in overview_data['modules'] if m['module_id']=='health']
if not health: raise SystemExit('ERROR: missing health snapshot')
health=health[0]
if health.get('source_health',{}).get('source_type') != 'local_probe': raise SystemExit('ERROR: health source type is not local_probe')
if health.get('status') not in {'ok','attention','degraded','offline'}: raise SystemExit('ERROR: invalid health status')
if len(health.get('kpis',[])) > 3: raise SystemExit('ERROR: health KPI count exceeds 3')
print('PASS: health local probe smoke passed')
PY
