#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Phase 4: 验证元素映射表在 PlaywrightExecutor 中的集成效果

模拟目标用例 case_13650e0406e64779b66e6fa5de35c24a 的步骤 7-9，
验证映射表能否正确命中并提供稳定选择器。
"""

import json
import logging
import os
import sys

# 添加 backend 到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

from app.services.element_mapping_service import ElementMappingService


def test_element_mapping():
    """验证元素映射表对目标用例步骤 7-9 的匹配效果"""
    svc = ElementMappingService()

    print("=" * 60)
    print("元素映射表集成验证 (Phase 3 & 4)")
    print("=" * 60)
    print(f"  映射表启用: {svc.is_enabled()}")
    print(f"  元素总数: {len(svc._elements)}")
    print()

    # 目标用例的关键步骤
    test_cases = [
        # (步骤描述, 动作, 预期映射键, 预期选择器)
        ("点击功能中心抽屉展开", "click",
         "导航栏-功能中心抽屉开关", ".home_nav_left"),

        ("点击【会议预约】分类", "click",
         "全部功能-筛选器-会议预约", "#reserve_enable"),

        ("点击【新建会议】按钮", "click",
         "首页-常用功能-创建会议", '[data-key="reserve_list.create"]'),

        # 额外测试：其他常见操作
        ("点击【数据统计】分类", "click",
         "全部功能-筛选器-数据统计", "#data_enable"),

        ("点击【会议列表】", "click",
         "首页-常用功能-会议列表", '[data-key="reserve_list.meeting"]'),

        ("点击【会议室】入口", "click",
         "首页-常用功能-会议室", '[data-key="reserve_list.room"]'),

        ("点击【创建会议】", "click",
         "首页-常用功能-创建会议", '[data-key="reserve_list.create"]'),

        ("点击【会议模板】", "click",
         "首页-常用功能-会议模板", '[data-key="reserve_list.model"]'),

        ("点击【会议日程】", "click",
         "首页-常用功能-会议日程", '[data-key="reserve_list.schedule"]'),

        # 筛选器测试
        ("点击筛选器中的会议预约分类", "click",
         "全部功能-筛选器-会议预约", "#reserve_enable"),

        ("点击筛选器中的数据统计分类", "click",
         "全部功能-筛选器-数据统计", "#data_enable"),

        # 导航栏抽屉
        ("点击功能中心抽屉开关", "click",
         "导航栏-功能中心抽屉开关", ".home_nav_left"),

        # 搜索框
        ("输入搜索关键词", "fill",
         "功能中心-搜索输入框", ".menu_header .search input"),
    ]

    passed = 0
    failed = 0

    for step_name, action, expected_key, expected_selector in test_cases:
        result = svc.get_selector(step_name, action)
        if result:
            actual_key = result["key"]
            actual_selector = result["selector"]
            conf = result["confidence"]

            # 断言：映射键和选择器都要匹配
            key_ok = expected_key in actual_key or actual_key in expected_key
            sel_ok = expected_selector == actual_selector

            status = "[PASS]" if (key_ok and sel_ok) else "[FAIL]"
            if "[PASS]" in status:
                passed += 1
            else:
                failed += 1

            print(f"  {status} [{action:6s}] {step_name}")
            print(f"      期望 -> key={expected_key}, sel={expected_selector}")
            print(f"      实际 -> key={actual_key}, sel={actual_selector}, conf={conf}")
        else:
            failed += 1
            print(f"  [FAIL] [{action:6s}] {step_name}")
            print(f"      期望 -> key={expected_key}, sel={expected_selector}")
            print(f"      实际 -> 未命中")
        print()

    print("=" * 60)
    print(f"结果: {passed}/{passed + failed} 通过, {failed} 失败")
    print("=" * 60)

    # 模拟 PlaywrightExecutor 集成效果
    print()
    print("=" * 60)
    print("模拟 PlaywrightExecutor 集成效果")
    print("=" * 60)
    print()

    # 模拟步骤 7-9 的执行流程
    steps_7_9 = [
        {"order": 7, "name": "点击功能中心抽屉展开", "action": "click",
         "params": {"selectors": [".home_nav_left"], "selector": ".home_nav_left"}},
        {"order": 8, "name": "点击【会议预约】分类", "action": "click",
         "params": {"selectors": ["#reserve_enable"], "selector": "#reserve_enable"}},
        {"order": 9, "name": "点击【新建会议】按钮", "action": "click",
         "params": {"selectors": ['[data-key="reserve_list.create"]'],
                    "selector": '[data-key="reserve_list.create"]'}},
    ]

    for step in steps_7_9:
        step_name = step["name"]
        step_action = step["action"]
        mapping_result = svc.get_selector(step_name, step_action)

        if mapping_result:
            mapping_selector = mapping_result["selector"]
            # 模拟注入到 params
            existing_selectors = step["params"].get("selectors", [])
            if existing_selectors:
                final_selectors = [mapping_selector] + list(existing_selectors)
            else:
                final_selectors = [mapping_selector]

            print(f"  [PASS] 步骤 {step['order']}: {step_name}")
            print(f"     [映射表] 命中: {step_name} -> {mapping_selector}")
            print(f"     [params] 注入后 selectors: {final_selectors}")
            print(f"     [params] selector: {mapping_selector}")
        else:
            print(f"  [WARN] 步骤 {step['order']}: {step_name}")
            print(f"     [映射表] 未命中，使用原有选择器: {step['params'].get('selectors')}")
        print()

    return failed == 0


if __name__ == "__main__":
    success = test_element_mapping()
    sys.exit(0 if success else 1)