#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试脚本：验证智能定位 API 端到端功能

测试内容：
1. 健康检查
2. 智能定位 - 信息发布模块导航验证
"""

import requests
import json
import sys

BASE_URL = "http://localhost:8002"


def test_health():
    """测试健康检查"""
    print("\n1. 健康检查...")
    resp = requests.get(f"{BASE_URL}/api/element/health")
    print(f"   Status: {resp.status_code}")
    if resp.status_code == 200:
        data = resp.json()
        print(f"   Service: {data.get('service', 'N/A')}")
        print(f"   Status: {data.get('status', 'N/A')}")
    else:
        print(f"   Error: {resp.text}")


def test_smart_locate():
    """测试智能定位"""
    print("\n2. 智能定位 - 信息发布模块...")

    # 构造请求：模拟用户录入的自然语言步骤
    # 注意：auto_login=True 时，系统会自动执行登录模板
    # 所以用户步骤只需要从登录后的操作开始
    request_data = {
        "steps": [
            # 登录后的操作步骤（登录由 auto_login 自动完成）
            {"order": 1, "name": "点击新增按钮", "action": "click", "params": {}},
            {"order": 2, "name": "等待页面加载", "action": "wait", "params": {"timeout": 10000}},
        ],
        "auto_login": True,
        "navigate_menu": "信息发布",
        "page_url": "https://192.168.5.44"
    }

    print(f"   Request: {json.dumps(request_data, ensure_ascii=False, indent=2)}")
    print("   Sending request (this may take 30-60 seconds)...")

    try:
        resp = requests.post(
            f"{BASE_URL}/api/element/smart-locate",
            json=request_data,
            timeout=120  # 2 分钟超时
        )
        print(f"   Status: {resp.status_code}")

        if resp.status_code == 200:
            data = resp.json()
            print(f"   Success: {data.get('success')}")
            print(f"   Total: {data.get('total_steps')}")
            print(f"   Located: {data.get('located_steps')}")
            print(f"   Message: {data.get('message')}")

            for result in data.get('results', []):
                status = "[OK]" if result.get('success') else "[FAIL]"
                selector = result.get('params', {}).get('selector', 'N/A')
                print(f"      {status} Step {result.get('order')}: {result.get('name')} -> {selector}")
                if result.get('message'):
                    print(f"         Message: {result.get('message')}")
        else:
            print(f"   Error: {resp.text}")

    except requests.exceptions.Timeout:
        print("   [TIMEOUT] Request timed out after 120 seconds")
    except Exception as e:
        print(f"   [ERROR] {e}")


def test_login_templates():
    """测试登录模板 API"""
    print("\n3. 登录模板 API...")
    resp = requests.get(f"{BASE_URL}/api/login-templates")
    print(f"   Status: {resp.status_code}")
    if resp.status_code == 200:
        data = resp.json()
        print(f"   Total: {data.get('total')}")
        for item in data.get('items', []):
            print(f"      - {item.get('name')} (type={item.get('template_type')}, steps={len(item.get('steps', []))})")
    else:
        print(f"   Error: {resp.text}")


if __name__ == "__main__":
    print("=" * 60)
    print("智能定位 API 端到端测试")
    print("=" * 60)

    test_health()
    test_login_templates()
    test_smart_locate()

    print("\n" + "=" * 60)
    print("测试完成")
    print("=" * 60)