#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：test_smart_locate_e2e.py
模块描述：智能定位端到端测试脚本

作者：czj
创建日期：2026-08-05
最后修改：2026-08-05
"""

import sys
import os

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

import asyncio
from app.services.smart_locate_service import SmartLocateService
from app.services.login_template_service import LoginTemplateService
from app.database import get_db, async_session_maker


async def test_login_templates():
    """测试登录模板服务"""
    print("\n" + "=" * 60)
    print("测试登录模板服务")
    print("=" * 60)

    async with async_session_maker() as db:
        service = LoginTemplateService(db)

        # 获取模板列表
        templates, total = await service.get_list()
        print(f"\n[OK] 模板列表: {total} 个模板")

        for t in templates:
            steps_count = len(t.steps) if t.steps else 0
            print(f"   - {t.name} ({t.template_type}): {steps_count} 步骤")

        # 获取默认登录模板
        login_template = await service.get_default_template("login")
        if login_template:
            print(f"\n[OK] 默认登录模板: {login_template.name}")
            print(f"   步骤数: {len(login_template.steps)}")
            for i, step in enumerate(login_template.steps, 1):
                print(f"   {i}. {step.get('name', 'N/A')} - {step.get('action', 'N/A')}")

        # 获取默认导航模板
        nav_template = await service.get_default_template("navigate")
        if nav_template:
            print(f"\n[OK] 默认导航模板: {nav_template.name}")
            print(f"   步骤数: {len(nav_template.steps)}")

        return True


async def test_smart_locate():
    """测试智能定位服务"""
    print("\n" + "=" * 60)
    print("测试智能定位服务")
    print("=" * 60)

    # 测试用例：会议管理 - 新增会议
    test_steps = [
        {"order": 1, "name": "点击新增按钮", "action": "click", "params": {}},
        {"order": 2, "name": "等待对话框加载", "action": "wait", "params": {"timeout": 5000}},
        {"order": 3, "name": "输入会议主题", "action": "fill", "params": {"value": "测试会议"}},
        {"order": 4, "name": "点击确定按钮", "action": "click", "params": {}},
    ]

    print("\n测试步骤:")
    for step in test_steps:
        print(f"   {step['order']}. {step['name']} ({step['action']})")

    service = SmartLocateService()

    try:
        # locate_steps 是同步方法，需要在线程池中运行
        import asyncio
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(
            None,
            service.locate_steps,
            test_steps,
            True,  # auto_login
            "会议管理",  # navigate_menu
            "https://192.168.5.44"  # page_url
        )

        print(f"\n定位结果:")
        print(f"   总步骤: {len(result)}")
        located_steps = sum(1 for r in result if r.get("success"))
        print(f"   成功定位: {located_steps}")

        for r in result:
            status = "[OK]" if r.get("success") else "[FAIL]"
            print(f"\n   {status} 步骤 {r['order']}: {r['name']}")
            if r.get("success"):
                print(f"      主选择器: {r['selectors'].get('primary', 'N/A')}")
            else:
                print(f"      失败原因: {r.get('message', 'N/A')}")

        return located_steps > 0

    except Exception as e:
        print(f"\n[ERROR] 测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


async def main():
    """主测试流程"""
    print("\n" + "=" * 60)
    print("智能定位端到端测试")
    print("=" * 60)
    print(f"被测系统: https://192.168.5.44")
    print(f"测试菜单: 会议管理")
    print(f"验证码: csba (固定)")

    results = []

    # 测试1: 登录模板
    try:
        r1 = await test_login_templates()
        results.append(("登录模板服务", r1))
    except Exception as e:
        print(f"\n[ERROR] 登录模板测试失败: {e}")
        results.append(("登录模板服务", False))

    # 测试2: 智能定位
    try:
        r2 = await test_smart_locate()
        results.append(("智能定位服务", r2))
    except Exception as e:
        print(f"\n[ERROR] 智能定位测试失败: {e}")
        results.append(("智能定位服务", False))

    # 汇总结果
    print("\n" + "=" * 60)
    print("测试汇总")
    print("=" * 60)

    for name, passed in results:
        status = "[OK] 通过" if passed else "[FAIL] 失败"
        print(f"   {name}: {status}")

    all_passed = all(r[1] for r in results)
    print("\n" + ("全部测试通过！" if all_passed else "部分测试失败"))

    return all_passed


if __name__ == "__main__":
    asyncio.run(main())