"""
部署冒烟测试脚本
在 docker-compose up -d --build 之后运行，验证系统可用性。
"""

import time
import urllib.request
import urllib.error
import sys


def check_endpoint(url: str, expect_in_body: str | None = None, label: str = "") -> bool:
    """
    轮询检查一个 HTTP 端点是否可达（最多重试 10 次，每次间隔 3 秒）。
    """
    for attempt in range(1, 11):
        try:
            req = urllib.request.Request(url)
            with urllib.request.urlopen(req, timeout=10) as resp:
                status = resp.status
                body = resp.read().decode("utf-8", errors="replace")

                if status == 200:
                    if expect_in_body and expect_in_body not in body:
                        print(f"  [{label}] 尝试 {attempt}/10 — 状态 200 但响应体不含 '{expect_in_body}'")
                        continue
                    print(f"  ✅ [{label}] PASS — HTTP {status}")
                    return True
                else:
                    print(f"  [{label}] 尝试 {attempt}/10 — HTTP {status}")
        except urllib.error.URLError as e:
            print(f"  [{label}] 尝试 {attempt}/10 — 连接失败: {e.reason}")
        except Exception as e:
            print(f"  [{label}] 尝试 {attempt}/10 — 异常: {e}")

        time.sleep(3)

    print(f"  ❌ [{label}] FAIL — 超过最大重试次数")
    return False


def main():
    print("\n" + "=" * 50)
    print("  SHBL-CRM 部署冒烟测试")
    print("=" * 50 + "\n")

    results = []

    # 验证点 1: 前端静态资源
    print("[1/2] 检测前端页面 (http://localhost/) ...")
    results.append(check_endpoint(
        url="http://localhost/",
        expect_in_body="<html",
        label="前端 SPA",
    ))

    # 验证点 2: Nginx → FastAPI 反代穿透
    print("\n[2/2] 检测后端 API 反代 (http://localhost/api/docs) ...")
    results.append(check_endpoint(
        url="http://localhost/api/docs",
        label="API 反代",
    ))

    # 汇总
    print("\n" + "-" * 50)
    if all(results):
        print("🎉 所有检查通过！系统已就绪。")
        sys.exit(0)
    else:
        print("⚠️  部分检查未通过，请排查容器日志：docker-compose logs -f")
        sys.exit(1)


if __name__ == "__main__":
    main()
