"""诊断 student/parent 登录问题"""
from playwright.sync_api import sync_playwright

BASE_URL = "http://localhost:3000"

ACCOUNTS = [
    ("student", "student_g1c1_1@xiaoxue.edu.cn", "123456", "/student/dashboard"),
    ("parent", "parent_g1c1_1@xiaoxue.edu.cn", "123456", "/parent/dashboard"),
]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    for role, email, password, expected_path in ACCOUNTS:
        print(f"\n=== 测试 {role} 登录 ===")
        context = browser.new_context()
        page = context.new_page()

        # 监听控制台
        console_msgs = []
        page.on("console", lambda msg: console_msgs.append(f"[{msg.type}] {msg.text}") if msg.type == "error" else None)

        # 监听响应
        responses = []
        def on_response(resp):
            if resp.status >= 400:
                responses.append(f"{resp.status} {resp.url}")
        page.on("response", on_response)

        try:
            page.goto(f"{BASE_URL}/login", timeout=30000)
            page.wait_for_load_state("networkidle", timeout=15000)
            print(f"  登录页 URL: {page.url}")

            # 填写表单
            email_input = page.locator('input[name="email"]')
            if email_input.count() == 0:
                email_input = page.locator('input[type="email"]')
            email_input.fill(email)

            password_input = page.locator('input[name="password"]')
            if password_input.count() == 0:
                password_input = page.locator('input[type="password"]')
            password_input.fill(password)

            # 点击登录
            login_btn = page.locator('button[type="submit"]')
            if login_btn.count() == 0:
                login_btn = page.get_by_role("button", name="Sign In with Email")
            login_btn.click()

            page.wait_for_timeout(5000)
            page.wait_for_load_state("networkidle", timeout=15000)

            print(f"  登录后 URL: {page.url}")
            print(f"  预期路径: {expected_path}")

            # 检查页面内容
            body_text = page.locator("body").text_content() or ""
            if "onboarding" in page.url.lower():
                print(f"  ⚠️ 被重定向到 onboarding 页面")
            elif "/login" in page.url:
                print(f"  ❌ 仍在登录页")
                # 查找错误消息
                error_msg = page.locator('[class*="error"], [class*="alert"], [role="alert"]').text_content()
                if error_msg:
                    print(f"  错误消息: {error_msg[:200]}")
            elif expected_path in page.url:
                print(f"  ✅ 登录成功")
            else:
                print(f"  ⚠️ 跳转到其他页面")

            # 打印控制台错误
            if console_msgs:
                print(f"  控制台错误 ({len(console_msgs)} 条):")
                for msg in console_msgs[:5]:
                    print(f"    {msg[:200]}")

            # 打印错误响应
            if responses:
                print(f"  错误响应 ({len(responses)} 条):")
                for r in responses[:5]:
                    print(f"    {r[:200]}")

        except Exception as e:
            print(f"  ❌ 异常: {e}")
        finally:
            context.close()

    browser.close()
