"""测试备课编辑页是否可用，捕获控制台错误。"""
from playwright.sync_api import sync_playwright

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

    errors = []
    console_msgs = []

    page.on("console", lambda msg: console_msgs.append(f"[{msg.type}] {msg.text}"))
    page.on("pageerror", lambda err: errors.append(str(err)))

    # 0. 登录
    print("=== 0. 登录 ===")
    page.goto("http://localhost:3000/login", wait_until="networkidle", timeout=30000)
    print(f"登录页URL: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_login.png", full_page=True)

    # 填写登录表单
    email_input = page.locator("input[type='email'], input[name='email']").first
    email_input.fill("t_chinese_1@xiaoxue.edu.cn")
    print("已填写邮箱")

    pw_input = page.locator("input[type='password'], input[name='password']").first
    pw_input.fill("123456")
    print("已填写密码")

    # 提交 - 按钮文本是 "Sign In with Email"
    submit = page.get_by_role("button", name="Sign In", exact=False).first
    submit.click()
    try:
        page.wait_for_url("**/dashboard**", timeout=15000)
    except Exception:
        try:
            page.wait_for_load_state("networkidle", timeout=10000)
        except Exception:
            pass
    print(f"登录后URL: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_after_login.png", full_page=True)

    # 1. 访问列表页
    print("\n=== 1. 访问列表页 ===")
    page.goto("http://localhost:3000/teacher/lesson-plans", wait_until="networkidle", timeout=30000)
    print(f"列表页URL: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_list.png", full_page=True)

    # 2. 访问新建页
    print("\n=== 2. 访问新建页 ===")
    page.goto("http://localhost:3000/teacher/lesson-plans/new", wait_until="networkidle", timeout=30000)
    print(f"新建页URL: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_new.png", full_page=True)

    # 填写标题
    title_input = page.locator("input").first
    title_input.fill("测试课案_v2")
    print("已填写标题")

    # 选择"常规课"模板
    template_btn = page.get_by_role("button", name="常规课", exact=False).first
    if template_btn.count() > 0:
        template_btn.click()
        print("已选择常规课模板")
    else:
        print("未找到常规课模板按钮，尝试其他选择器")
        # 用文本找包含"课"的按钮
        all_btns = page.locator("button[type='button']").all()
        for b in all_btns:
            txt = b.inner_text()
            if "课" in txt:
                b.click()
                print(f"已点击模板: {txt}")
                break

    # 创建
    submit_btn = page.get_by_role("button", name="创建课案", exact=False).first
    if submit_btn.count() == 0:
        submit_btn = page.locator("button").last
    print("点击创建")
    submit_btn.click()
    try:
        page.wait_for_load_state("networkidle", timeout=15000)
    except Exception as e:
        print(f"等待超时: {e}")
    print(f"创建后URL: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_after_create.png", full_page=True)

    # 3. 编辑页检查
    print("\n=== 3. 编辑页检查 ===")
    if "/edit" in page.url:
        print("成功进入编辑页")
        page.wait_for_timeout(5000)
        page.screenshot(path="e:/Desktop/CICD/bugs/v2_edit.png", full_page=True)
        # 检查页面内容
        body_text = page.locator("body").inner_text()
        print(f"页面文本长度: {len(body_text)}")
        print(f"页面文本前200字: {body_text[:200]}")
    else:
        print(f"未进入编辑页，当前URL: {page.url}")

    # 4. 错误输出
    print("\n=== 4. 页面错误 ===")
    if errors:
        for e in errors:
            print(f"  ERROR: {e}")
    else:
        print("  无页面错误")

    print("\n=== 5. 控制台错误/警告 ===")
    for m in console_msgs:
        if m.startswith("[error]") or m.startswith("[warning]"):
            print(f"  {m}")

    browser.close()
    print("\n完成")
