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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

echo "[smoke] checking dev containers"
docker ps --format '{{.Names}}' | grep -qx 'mh-dashboard-organization-dev-backend-1'
docker ps --format '{{.Names}}' | grep -qx 'mh-dashboard-organization-dev-proxy-1'

echo "[smoke] running 8081 endpoint checks"
docker exec mh-dashboard-organization-dev-backend-1 python - <<'PY'
import sys
import urllib.request


checks = [
    ("health", "http://127.0.0.1:8000/api/health", b'"status"'),
    ("db-status-api", "http://127.0.0.1:8000/api/admin/db-status", b'"tables"'),
    ("ledger-default-api", "http://127.0.0.1:8000/api/integration/business-ledger-default", b'PK'),
    ("legacy-organization", "http://127.0.0.1:8000/legacy/organization", b'organization'),
    ("payment", "http://127.0.0.1:8000/integrations/payment", b'const App = () =>'),
    ("ledger", "http://127.0.0.1:8000/integrations/ledger", b'xlsx.full.min.js'),
    ("mh", "http://127.0.0.1:8000/integrations/mh", b'const App = () =>'),
    ("proxy-root", "http://proxy/", b'app.js'),
    ("proxy-db-status", "http://proxy/db-status.html", b'전체 테이블 현황'),
]

failed = []

for name, url, needle in checks:
    try:
        with urllib.request.urlopen(url, timeout=8) as response:
            body = response.read()
            status = getattr(response, "status", response.getcode())
            if status != 200:
                failed.append(f"{name}: unexpected status {status}")
                continue
            if needle not in body:
                failed.append(f"{name}: missing expected marker {needle!r}")
                continue
            print(f"[ok] {name} -> {status}")
    except Exception as exc:
        failed.append(f"{name}: {exc}")

if failed:
    print("[smoke] failures detected:")
    for item in failed:
        print(f" - {item}")
    sys.exit(1)

print("[smoke] all checks passed")
PY
