#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
更新测试用例选择器脚本

使用更精确的选择器更新现有测试用例。
"""

import asyncio
import json
from pathlib import Path
import sys

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

from app.database import async_session_maker, init_db
from app.models.test_case import TestCase
from app.utils.selector_mapper import SELECTORS, get_smart_selector
from sqlalchemy import select


# 选择器优化映射
SELECTOR_IMPROVEMENTS = {
    # 登录相关
    "用户名输入框": "input[placeholder*='用户']",
    "密码输入框": "input[type='password']",
    "验证码输入框": "input[placeholder*='验证']",
    "登录按钮": "button:has-text('登录')",
    "协议确认按钮": ".el-dialog button:has-text('确定')",

    # 通用
    "搜索输入框": "input[placeholder*='搜索']",
    "搜索按钮": "button:has-text('搜索')",
    "新建按钮": "button:has-text('新建')",
    "确认按钮": "button:has-text('确定')",
    "取消按钮": "button:has-text('取消')",

    # 列表
    "表格": ".el-table",
    "列表": ".el-table",
    "表单": ".el-form",
}


async def update_case_selectors():
    """更新测试用例的选择器"""
    await init_db()

    async with async_session_maker() as db:
        query = select(TestCase)
        result = await db.execute(query)
        cases = list(result.scalars().all())

        updated_count = 0

        for case in cases:
            steps = case.steps
            if not steps:
                continue

            has_update = False

            for step in steps:
                params = step.get("params", {})
                action = step.get("action", "")
                step_name = step.get("name", "")
                old_selector = params.get("selector", "")

                # 优化选择器
                if action in ["click", "fill", "wait", "assert", "hover"]:
                    if old_selector in ["body", ".el-button", "button", ".el-input", "input"]:
                        # 根据步骤名称推断更精确的选择器
                        for key, new_selector in SELECTOR_IMPROVEMENTS.items():
                            if key in step_name:
                                params["selector"] = new_selector
                                has_update = True
                                print(f"[{case.name}] Updated selector: {old_selector} -> {new_selector}")
                                break

                # 优化断言选择器
                if action == "assert":
                    assert_type = params.get("type", "")
                    if assert_type == "visible" and old_selector == "body":
                        if "表单" in step_name:
                            params["selector"] = ".el-form, form"
                            has_update = True
                        elif "表格" in step_name or "列表" in step_name:
                            params["selector"] = ".el-table, table"
                            has_update = True
                        elif "卡片" in step_name:
                            params["selector"] = ".card, .el-card"
                            has_update = True
                        elif "图表" in step_name:
                            params["selector"] = ".chart, canvas"
                            has_update = True

            if has_update:
                case.steps = steps
                updated_count += 1

        await db.commit()
        print(f"\nUpdated {updated_count} test cases")


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