#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [[ -z "${FINANCE_API_BASE_URL:-}" ]]; then
  echo "ERROR: FINANCE_API_BASE_URL is not set. Start FinanceManager locally and export FINANCE_API_BASE_URL=http://127.0.0.1:<port>" >&2
  exit 1
fi
python3 - <<'PY'
import json, os
from urllib.parse import urlparse
from urllib.request import urlopen, Request
url=os.environ['FINANCE_API_BASE_URL'].rstrip('/')
parsed=urlparse(url)
if parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1','localhost'}:
    raise SystemExit('ERROR: FINANCE_API_BASE_URL must be local http://127.0.0.1:<port> or http://localhost:<port> for live smoke')
for endpoint in ['/api/health','/api/provider/status','/api/runtime/status','/api/system/status','/api/budget/import-status-audit']:
    req=Request(url+endpoint, method='GET', headers={'accept':'application/json'})
    with urlopen(req, timeout=5) as response:
        if response.status != 200:
            raise SystemExit(f'ERROR: FinanceManager {endpoint} returned {response.status}')
        json.loads(response.read().decode())
print('OK: allowed FinanceManager GET endpoints reachable')
PY
PORT="${JARVIS_SMOKE_GATEWAY_PORT:-18080}"
TMP_DIR="$ROOT/.tmp/finance-live-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"
  FINANCE_ADAPTER_MODE=live_readonly ALLOW_EXACT_FINANCE_VALUES=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=['amount_chf','cash_value_chf','total_value_chf','portfolio_value_chf','balance','saldo','transaction','account_name','iban','/home/agent','traceback','token','secret','password','api_key','finance.sqlite','csv','xlsx','pdf']
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 finance string leaked: {bad}')
        if path == '/api/modules':
            modules_data=data
        if path == '/api/overview':
            overview_data=data
finance_registry=[m for m in modules_data if m.get('module_id')=='finance']
if not finance_registry: raise SystemExit('ERROR: missing finance registry entry')
if finance_registry[0].get('source_type') != 'http_api': raise SystemExit('ERROR: finance registry source_type is not http_api; live_readonly not active')
finance=[m for m in overview_data['modules'] if m['module_id']=='finance']
if not finance: raise SystemExit('ERROR: missing finance snapshot')
finance=finance[0]
if finance.get('source_health',{}).get('source_type') != 'http_api': raise SystemExit('ERROR: finance source_health source_type is not http_api')
if finance.get('status') not in {'ok','attention','degraded','offline'}: raise SystemExit('ERROR: invalid finance status')
print('PASS: finance live readonly smoke passed')
PY
