#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试智能定位 API 端到端流程
"""
import requests
import json

BASE_URL = "http://localhost:8001"

def test_smart_locate_api():
    """测试智能定位 API"""
    print("\n" + "=" * 60)
    print("测试智能定位 API")
    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": {}},
    ]

    payload = {
        "steps": test_steps,
        "auto_login": True,
        "navigate_menu": "会议管理",
        "page_url": "https://192.168.5.44"
    }

    print("\n请求参数:")
    print(json.dumps(payload, indent=2, ensure_ascii=False))

    print("\n发送请求...")
    try:
        response = requests.post(
            f"{BASE_URL}/api/element/smart-locate",
            json=payload,
            timeout=180
        )

        print(f"响应状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            print("\n响应结果:")
            print(json.dumps(result, indent=2, ensure_ascii=False))

            print("\n定位汇总:")
            print(f"  总步骤: {result.get('total_steps', 0)}")
            print(f"  成功定位: {result.get('located_steps', 0)}")

            for r in result.get("results", []):
                status = "[OK]" if r.get("success") else "[FAIL]"
                print(f"  {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 result.get("located_steps", 0) > 0
        else:
            print(f"请求失败: {response.text}")
            return False

    except Exception as e:
        print(f"请求异常: {e}")
        return False

if __name__ == "__main__":
    test_smart_locate_api()