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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$ROOT/.tmp/health-safe-marker-smoke"
MARKER="$TMP_DIR/safe-marker.json"
OVERVIEW="$TMP_DIR/overview.json"
MODULES="$TMP_DIR/modules.json"
LOG="$TMP_DIR/gateway.log"
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"
NOW="$(python3 - <<'PY'
from datetime import datetime, timezone
print(datetime.now(timezone.utc).isoformat().replace('+00:00','Z'))
PY
)"
cat > "$MARKER" <<JSON
{
  "schema_version": "1.0",
  "generated_at": "$NOW",
  "source": "healthmanager_safe_status",
  "pipeline_freshness": "fresh",
  "backup_freshness": "fresh",
  "review_count": 0,
  "source_reachable": "yes",
  "last_success_at": "$NOW",
  "status": "ok",
  "notes_category": "none"
}
JSON

PORT="$(python3 - <<'PY'
import socket
s=socket.socket(); s.bind(('127.0.0.1',0)); print(s.getsockname()[1]); s.close()
PY
)"
cd "$ROOT/apps/api-gateway"
HEALTH_ADAPTER_MODE=safe_marker \
HEALTH_SAFE_STATUS_MARKER_PATH="$MARKER" \
HEALTH_SAFE_STATUS_MAX_AGE_HOURS=72 \
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, sys
from pathlib import Path
root=Path('$TMP_DIR')
overview=json.loads(Path('$OVERVIEW').read_text())
modules=json.loads(Path('$MODULES').read_text())
text=json.dumps({'overview': overview, 'modules': modules})
health=next(m for m in overview['modules'] if m['module_id']=='health')
assert health['source_health']['source_type']=='safe_marker'
assert health['primary_action']['href']=='/health'
assert health['primary_action']['mode']=='link_only'
assert len(health['kpis']) <= 3
for forbidden in ['diagnosis','medication','symptom','/home/agent', str(Path('$MARKER')), 'safe-marker.json', 'Traceback', 'SEC'+'RET=', 'TOK'+'EN=']:
    if forbidden in text:
        raise SystemExit(f'forbidden smoke output: {forbidden}')
health_module=next(m for m in modules if m['module_id']=='health')
assert health_module['source_type']=='safe_marker'
print('health-safe-marker smoke PASS: overview/modules safe_marker, no forbidden strings, no marker path leak')
PY
