"""快速诊断备课模块 500 错误"""
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()

    # 收集控制台错误和页面错误
    console_msgs = []
    page_errors = []

    def on_console(msg):
        console_msgs.append(f"[{msg.type}] {msg.text}")

    def on_pageerror(err):
        page_errors.append(str(err))

    page.on("console", on_console)
    page.on("pageerror", on_pageerror)

    # 登录教师账号
    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_load_state("networkidle", timeout=20000)
    page.wait_for_timeout(2000)
    print(f"登录后 URL: {page.url}")

    # 访问备课列表页
    print("\n>>> 访问 /teacher/lesson-plans...")
    try:
        response = page.goto(f"{BASE_URL}/teacher/lesson-plans", timeout=30000)
        print(f"HTTP 状态: {response.status if response else 'None'}")
        print(f"最终 URL: {page.url}")
        page.wait_for_load_state("networkidle", timeout=15000)
        page.wait_for_timeout(2000)

        # 截图
        page.screenshot(path="webtest/screenshots/lesson-preparation/diag_teacher_list.png", full_page=True)

        # 检查页面内容
        body_text = page.locator("body").text_content() or ""
        print(f"\n页面内容长度: {len(body_text)}")
        print(f"页面内容前 500 字符: {body_text[:500]}")

        # 检查是否有错误提示
        error_elements = page.locator('[role="alert"], .text-destructive, .text-red-500, .text-red-600').all()
        for et in error_elements[:5]:
            text = et.text_content()
            if text:
                print(f"错误提示: {text.strip()[:200]}")

    except Exception as e:
        print(f"❌ 访问失败: {e}")

    print("\n>>> 控制台消息:")
    for msg in console_msgs[-20:]:
        print(f"  {msg}")

    print("\n>>> 页面错误:")
    for err in page_errors:
        print(f"  {err}")

    # 也尝试访问新建页
    print("\n>>> 访问 /teacher/lesson-plans/new...")
    try:
        response = page.goto(f"{BASE_URL}/teacher/lesson-plans/new", timeout=30000)
        print(f"HTTP 状态: {response.status if response else 'None'}")
        print(f"最终 URL: {page.url}")
        page.wait_for_load_state("networkidle", timeout=15000)
        page.wait_for_timeout(1000)
        page.screenshot(path="webtest/screenshots/lesson-preparation/diag_teacher_new.png", full_page=True)
    except Exception as e:
        print(f"❌ 访问新建页失败: {e}")

    browser.close()
