"""测试备课编辑页 - 用精确选择器"""
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)
    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="Sign In", exact=False).click()
    try:
        page.wait_for_url("**/dashboard**", timeout=15000)
    except Exception:
        page.wait_for_load_state("networkidle", timeout=10000)
    print(f"登录后: {page.url}")

    # 1. 新建页
    print("\n=== 1. 新建页 ===")
    page.goto("http://localhost:3000/teacher/lesson-plans/new", wait_until="networkidle", timeout=30000)
    print(f"新建页: {page.url}")

    # 用 name 属性精确定位标题输入框
    title_input = page.locator("input[placeholder*='秋天']").first
    if title_input.count() == 0:
        title_input = page.locator("form input").first
    title_input.fill("测试课案v2")
    print("已填标题")

    # 用 CSS 选择器精确匹配模板按钮
    template_btn = page.locator("button[type='button']:has-text('常规课')")
    print(f"模板按钮数量: {template_btn.count()}")
    template_btn.click()
    page.wait_for_timeout(500)
    print("已点常规课模板")

    # 检查创建按钮状态
    create_btn = page.get_by_role("button", name="创建课案", exact=False)
    is_disabled = create_btn.is_disabled()
    print(f"创建按钮 disabled: {is_disabled}")

    if is_disabled:
        # 调试：检查页面所有按钮
        all_btns = page.locator("button").all()
        print(f"页面按钮总数: {len(all_btns)}")
        for i, b in enumerate(all_btns):
            txt = b.inner_text()[:50]
            btn_type = b.get_attribute("type")
            print(f"  btn[{i}]: type={btn_type} text='{txt}'")

    # 强制点击创建
    create_btn.click(force=True)
    try:
        page.wait_for_url("**/edit**", timeout=15000)
    except Exception as e:
        print(f"等待跳转: {e}")
    print(f"创建后: {page.url}")
    page.screenshot(path="e:/Desktop/CICD/bugs/v2_after_create.png", full_page=True)

    # 2. 编辑页检查
    print("\n=== 2. 编辑页 ===")
    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 = page.locator("body").inner_text()
        print(f"页面文本长度: {len(body)}")
        print(f"前300字:\n{body[:300]}")
    else:
        print(f"未进入编辑页: {page.url}")

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

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

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