"""获取 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()

    # 监听响应，捕获 500 错误的响应体
    error_responses = []

    def on_response(response):
        if response.status >= 400:
            url = response.url
            if 'lesson-plans' in url and '_rsc' not in url:
                try:
                    body = response.text()
                    error_responses.append((response.status, url, body))
                    print(f"\n[捕获 {response.status}] {url[:100]}")
                    print(f"响应长度: {len(body)}")
                except Exception as e:
                    print(f"[error] 无法读取响应: {e}")

    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_timeout(5000)
    print(f"登录后 URL: {page.url}")

    print("\n>>> 访问 /teacher/lesson-plans...")
    response = page.goto(f"{BASE_URL}/teacher/lesson-plans", timeout=30000, wait_until="domcontentloaded")
    page.wait_for_timeout(3000)

    # 输出所有捕获的错误响应
    print(f"\n\n=== 捕获到 {len(error_responses)} 个错误响应 ===")
    for status, url, body in error_responses:
        print(f"\n--- {status} {url[:100]} ---")
        # 找到错误消息
        error_messages = re.findall(r'data-next-error-message="([^"]+)"', body)
        if error_messages:
            for msg in error_messages:
                msg = msg.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&#x27;", "'").replace("&amp;", "&")
                print(f"\n错误消息:\n{msg}")

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

        # 如果没有找到错误消息，输出前 2000 字符
        if not error_messages and not error_stacks:
            print(f"\n响应前 2000 字符:\n{body[:2000]}")

    browser.close()
