"""
测试协议弹窗点击修复

运行方式: cd backend && python test_protocol_dialog.py

验证项:
1. 协议弹窗等待
2. 复选框勾选
3. 多选择器回退
4. 多点击方式回退
"""

import sys
import os

# 添加 backend 目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.executors.playwright_executor import PlaywrightExecutor


def test_login_with_protocol_dialog():
    """测试登录流程中的协议弹窗处理"""
    executor = PlaywrightExecutor(
        config={
            "headless": False,  # 非无头模式，方便观察
            "timeout": 30000,
        }
    )

    try:
        print("=" * 60)
        print("测试协议弹窗点击修复")
        print("=" * 60)

        # 启动执行器
        print("\n1. 启动 Playwright 执行器...")
        executor.start()
        print("   ✓ 执行器启动成功")

        # 执行自动登录
        print("\n2. 执行自动登录...")
        print("   - 访问登录页")
        print("   - 填写账号密码验证码")
        print("   - 点击登录按钮")
        print("   - 等待协议弹窗")
        print("   - 勾选复选框（如有）")
        print("   - 尝试多种点击方式")

        success = executor.do_login()

        if success:
            print("\n   ✓ 登录成功!")
            print(f"   当前 URL: {executor._page.url}")
            print(f"   登录状态: _is_logged_in = {executor._is_logged_in}")
        else:
            print("\n   ✗ 登录失败")
            print("   请检查日志输出，确认协议弹窗处理情况")

        return success

    except Exception as e:
        print(f"\n✗ 测试异常: {e}")
        import traceback
        traceback.print_exc()
        return False

    finally:
        print("\n3. 停止执行器...")
        executor.stop()
        print("   ✓ 执行器已停止")


if __name__ == "__main__":
    result = test_login_with_protocol_dialog()
    print("\n" + "=" * 60)
    if result:
        print("测试结果: ✓ 通过")
    else:
        print("测试结果: ✗ 失败")
    print("=" * 60)

    sys.exit(0 if result else 1)
