"""CDP E2E comprehensive test against real Electron app."""

from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from nomo_e2e import WebViewController


def test_cdp_full_interaction() -> None:
    print("=" * 60)
    print("CDP Full Interaction Test - Student Records Electron")
    print("=" * 60)

    endpoint = "http://localhost:9222"
    print(f"\n[1] 连接 CDP 端点: {endpoint}")

    controller = WebViewController.connect(endpoint, driver="cdp")
    print(f"    ✅ 连接成功! driver={controller.driver}")
    print(f"    ✅ URL: {controller.url}")
    print(f"    ✅ Title: {controller.title}")

    print("\n[2] 页面基础信息...")
    snapshot = controller.diagnostics_snapshot()
    print(f"    ✅ 页面状态: {snapshot['ready_state']}")
    print(f"    ✅ 标题: {snapshot['title']}")

    print("\n[3] 页面结构分析...")
    html = controller.execute_script(
        "return document.body ? document.body.innerHTML.substring(0, 300) : 'no body'"
    )
    print(f"    ✅ HTML 预览: {html[:150]}...")

    print("\n[4] 查找输入元素...")
    inputs = controller.execute_script(
        "return Array.from(document.querySelectorAll('input')).map(i => ({"
        "type: i.type, name: i.name, placeholder: i.placeholder}))"
    )
    print(f"    ✅ 找到 {len(inputs)} 个输入框:")
    for inp in inputs[:5]:
        print(f"       - type={inp.get('type')}, placeholder={inp.get('placeholder')}")

    print("\n[5] 查找按钮元素...")
    buttons = controller.execute_script(
        "return Array.from(document.querySelectorAll('button')).map(b => b.textContent.trim().substring(0, 20))"
    )
    print(f"    ✅ 找到 {len(buttons)} 个按钮:")
    for btn in buttons[:5]:
        print(f"       - {btn}")

    print("\n[6] 测试 get_text (获取元素文本)...")
    try:
        sidebar_text = controller.get_text(".sidebar-header")
        print(f"    ✅ .sidebar-header 文本: {sidebar_text[:30]}...")
    except Exception as e:
        print(f"    ⚠️ .sidebar-header 未找到: {e}")

    print("\n[7] 测试 screenshot...")
    screenshot_path = "/tmp/electron_cdp_full.png"
    try:
        controller.screenshot(screenshot_path)
        print(f"    ✅ 全页截图已保存: {screenshot_path}")
    except Exception as e:
        print(f"    ❌ 截图失败: {e}")

    print("\n[8] 测试 type_text (输入文本)...")
    try:
        search_input = "input[placeholder*='搜索']"
        if controller.wait_for_selector(search_input, timeout_ms=3000):
            controller.type_text(search_input, "张三")
            print("    ✅ 在搜索框输入文本成功")
        else:
            print("    ⚠️ 搜索框未找到")
    except Exception as e:
        print(f"    ⚠️ type_text 测试: {e}")

    print("\n[9] 测试 click (点击按钮)...")
    try:
        add_button = "button:has-text('添加学生')"
        if controller.wait_for_selector(add_button, timeout_ms=3000):
            controller.click(add_button)
            print("    ✅ 点击'添加学生'按钮成功")
        else:
            print("    ⚠️ '添加学生'按钮未找到")
    except Exception as e:
        print(f"    ⚠️ click 测试: {e}")

    print("\n[10] 断开连接...")
    controller.disconnect()
    print("    ✅ 断开成功")

    print("\n" + "=" * 60)
    print("✅ CDP 完整交互测试完成!")
    print("=" * 60)


if __name__ == "__main__":
    test_cdp_full_interaction()
