"""诊断 lesson-plans 页面 - 获取完整错误"""
import re
from playwright.sync_api import sync_playwright

BASE_URL = "http://localhost:3000"

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()

    # 监听控制台
    page.on("console", lambda msg: print(f"[console.{msg.type}] {msg.text[:500]}") if msg.type in ('error', 'warning') else None)
    page.on("pageerror", lambda err: print(f"[pageerror] {err}"))

    print(">>> 登录教师账号...")
    page.goto(f"{BASE_URL}/login", timeout=30000)
    page.wait_for_load_state("networkidle", timeout=15000)
    page.locator('input[name="email"]').fill("t_chinese_1@xiaoxue.edu.cn")
    page.locator('input[name="password"]').fill("123456")
    page.get_by_role("button", name=re.compile(r"Sign In with Email", re.I)).click()

    # 等待跳转完成
    page.wait_for_timeout(5000)
    print(f"登录后 URL: {page.url}")

    # 直接访问 lesson-plans
    print("\n>>> 访问 /teacher/lesson-plans...")
    response = page.goto(f"{BASE_URL}/teacher/lesson-plans", timeout=30000, wait_until="domcontentloaded")
    print(f"HTTP 状态: {response.status if response else 'None'}")

    page.wait_for_timeout(3000)
    print(f"最终 URL: {page.url}")

    # 获取页面完整内容
    body = page.content()
    print(f"\n页面内容长度: {len(body)}")

    # 找到所有 data-next-error-message 属性
    error_messages = re.findall(r'data-next-error-message="([^"]+)"', body)
    print(f"\n=== 错误消息 ({len(error_messages)} 条) ===")
    for msg in error_messages:
        # 解码 HTML 实体
        msg = msg.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&#x27;", "'").replace("&amp;", "&")
        print(f"\n--- 错误 ---")
        print(msg)

    # 也查找 error 属性
    error_codes = re.findall(r'data-next-error-code="([^"]+)"', body)
    if error_codes:
        print(f"\n=== 错误代码 ===")
        for code in error_codes:
            print(f"  {code}")

    # 查找 error 堆栈
    error_stacks = re.findall(r'data-next-error-stack="([^"]+)"', body)
    if error_stacks:
        print(f"\n=== 错误堆栈 ({len(error_stacks)} 条) ===")
        for stack in error_stacks[:1]:  # 只显示第一条
            stack = stack.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&#x27;", "'").replace("&amp;", "&")
            print(stack[:3000])

    # 截图
    page.screenshot(path="webtest/diag7_lesson_plans.png", full_page=True)
    print("\n截图已保存: webtest/diag7_lesson_plans.png")

    browser.close()
