"""验证后端服务可达：健康检查 + JWT 认证 + /api/tasks/flows 200"""
import urllib.request
import json
import sys

BASE = "http://localhost:8000"

def main():
    # 1. 健康检查
    try:
        r = urllib.request.urlopen(f"{BASE}/health")
        print(f"[OK] GET /health -> {r.status}")
    except Exception as e:
        print(f"[FAIL] GET /health -> {e}")
        sys.exit(1)

    # 2. 登录获取 JWT
    try:
        login_data = json.dumps({"username": "admin", "password": "admin123"}).encode()
        req = urllib.request.Request(
            f"{BASE}/api/auth/login",
            data=login_data,
            headers={"Content-Type": "application/json"},
        )
        resp = urllib.request.urlopen(req)
        body = json.loads(resp.read().decode())
        token = body["access_token"]
        print(f"[OK] POST /api/auth/login -> JWT obtained ({token[:20]}...)")
    except Exception as e:
        print(f"[FAIL] POST /api/auth/login -> {e}")
        sys.exit(1)

    # 3. 验证 /api/tasks/flows
    try:
        req2 = urllib.request.Request(
            f"{BASE}/api/tasks/flows",
            headers={"Authorization": f"Bearer {token}"},
        )
        resp2 = urllib.request.urlopen(req2)
        data = json.loads(resp2.read().decode())
        print(f"[OK] GET /api/tasks/flows -> {resp2.status}")
        if isinstance(data, list):
            print(f"     Flows count: {len(data)}")
            for f in data[:5]:
                print(f"     - {f}")
        else:
            preview = json.dumps(data, indent=2, ensure_ascii=False)[:300]
            print(f"     Response preview: {preview}")
    except Exception as e:
        print(f"[FAIL] GET /api/tasks/flows -> {e}")
        sys.exit(1)

    print("\n=== 后端服务验证通过 ===")

if __name__ == "__main__":
    main()
