"""详细诊断 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()

    # 收集所有响应
    responses = []

    def on_response(response):
        url = response.url
        status = response.status
        if "/teacher/lesson-plans" in url or "/api/" in url:
            responses.append({"url": url, "status": status})
            print(f"  [RESPONSE] {status} {url}")

    page.on("response", on_response)

    # 登录教师账号
    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(3000)
    print(f"登录后 URL: {page.url}")

    if "/login" in page.url:
        print("❌ 登录失败，尝试获取错误信息...")
        # 检查页面上的错误提示
        error_text = page.locator("body").text_content()
        print(f"页面内容: {error_text[:500] if error_text else 'empty'}")
    else:
        print("✅ 登录成功")

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

            # 等待更长时间
            try:
                page.wait_for_load_state("networkidle", timeout=30000)
            except:
                print("  networkidle 超时，继续检查...")

            page.wait_for_timeout(3000)

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

            # 检查是否有错误页面
            if "500" in body_text or "Error" in body_text or "错误" in body_text:
                print("\n⚠️ 检测到错误页面")
                # 获取完整的 HTML
                html = page.content()
                # 找到错误信息
                error_match = re.search(r'(Error|错误|error)[^<]{0,500}', html)
                if error_match:
                    print(f"错误信息: {error_match.group(0)}")

            page.screenshot(path="webtest/screenshots/lesson-preparation/diag2_list.png", full_page=True)

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

    print("\n>>> 所有响应:")
    for r in responses:
        print(f"  {r['status']} {r['url']}")

    browser.close()
