#!/usr/bin/env python3
"""
工作手机SDK v3.0 - 模拟器测试脚本
直接使用ADB命令控制模拟器
"""

import subprocess
import time
import base64
import json
import urllib.request

SDK_URL = "http://localhost:8899"
DEVICE_SERIAL = "emulator-5554"


def adb_shell(cmd: str) -> str:
    """执行ADB shell命令"""
    result = subprocess.run(
        ["adb", "-s", DEVICE_SERIAL, "shell", cmd],
        capture_output=True,
        text=True
    )
    return result.stdout.strip()


def adb_tap(x: int, y: int):
    """点击坐标"""
    adb_shell(f"input tap {x} {y}")


def adb_swipe(x1: int, y1: int, x2: int, y2: int, duration: int = 500):
    """滑动"""
    adb_shell(f"input swipe {x1} {y1} {x2} {y2} {duration}")


def adb_input_text(text: str):
    """输入文字"""
    # 转义特殊字符
    escaped = text.replace(" ", "%s").replace("'", "\\'")
    adb_shell(f"input text '{escaped}'")


def adb_screenshot() -> bytes:
    """截图"""
    result = subprocess.run(
        ["adb", "-s", DEVICE_SERIAL, "exec-out", "screencap", "-p"],
        capture_output=True
    )
    return result.stdout


def adb_start_app(package: str):
    """启动APP"""
    adb_shell(f"monkey -p {package} -c android.intent.category.LAUNCHER 1")


def adb_current_app() -> str:
    """获取当前APP"""
    output = adb_shell("dumpsys window | grep -E 'mCurrentFocus'")
    return output


def sdk_api(path: str, method: str = "GET", data: dict = None) -> dict:
    """调用SDK API"""
    url = f"{SDK_URL}{path}"
    
    if data:
        req = urllib.request.Request(
            url,
            data=json.dumps(data).encode(),
            headers={"Content-Type": "application/json"},
            method=method
        )
    else:
        req = urllib.request.Request(url, method=method)
    
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return json.loads(resp.read().decode())
    except Exception as e:
        return {"error": str(e)}


def test_sdk_health():
    """测试SDK健康"""
    print("=" * 50)
    print("测试1: SDK健康检查")
    result = sdk_api("/health")
    print(f"结果: {result}")
    return result.get("status") == "healthy"


def test_device_info():
    """测试获取设备信息"""
    print("=" * 50)
    print("测试2: 获取设备信息")
    
    model = adb_shell("getprop ro.product.model")
    version = adb_shell("getprop ro.build.version.release")
    size = adb_shell("wm size")
    
    print(f"型号: {model}")
    print(f"Android版本: {version}")
    print(f"屏幕: {size}")
    return True


def test_screenshot():
    """测试截图"""
    print("=" * 50)
    print("测试3: 截图")
    
    img = adb_screenshot()
    print(f"截图大小: {len(img)} bytes")
    
    # 保存截图
    with open("/tmp/sdk_test_screen.png", "wb") as f:
        f.write(img)
    print("已保存: /tmp/sdk_test_screen.png")
    return len(img) > 10000


def test_click():
    """测试点击"""
    print("=" * 50)
    print("测试4: 点击操作")
    
    # 点击屏幕中心
    adb_tap(540, 1200)
    time.sleep(1)
    print("点击 (540, 1200) 完成")
    return True


def test_swipe():
    """测试滑动"""
    print("=" * 50)
    print("测试5: 滑动操作")
    
    # 向上滑动
    adb_swipe(540, 1800, 540, 600, 500)
    time.sleep(1)
    print("向上滑动完成")
    
    # 向下滑动
    adb_swipe(540, 600, 540, 1800, 500)
    time.sleep(1)
    print("向下滑动完成")
    return True


def test_open_settings():
    """测试打开设置APP"""
    print("=" * 50)
    print("测试6: 打开设置APP")
    
    adb_start_app("com.android.settings")
    time.sleep(2)
    
    current = adb_current_app()
    print(f"当前APP: {current}")
    
    success = "settings" in current.lower()
    if success:
        print("✅ 设置APP已打开")
    return success


def test_input_text():
    """测试输入文字"""
    print("=" * 50)
    print("测试7: 输入文字")
    
    # 打开搜索
    adb_shell("am start -a android.intent.action.VIEW -d 'https://www.baidu.com'")
    time.sleep(3)
    
    print("已打开浏览器")
    return True


def main():
    print("🚀 工作手机SDK v3.0 - 模拟器完整测试")
    print("=" * 50)
    
    results = []
    
    # 检查设备连接
    devices = subprocess.run(["adb", "devices"], capture_output=True, text=True)
    if DEVICE_SERIAL not in devices.stdout:
        print(f"❌ 设备 {DEVICE_SERIAL} 未连接")
        return
    
    print(f"✅ 设备已连接: {DEVICE_SERIAL}\n")
    
    # 运行测试
    tests = [
        ("SDK健康检查", test_sdk_health),
        ("获取设备信息", test_device_info),
        ("截图功能", test_screenshot),
        ("点击操作", test_click),
        ("滑动操作", test_swipe),
        ("打开设置APP", test_open_settings),
    ]
    
    for name, test_func in tests:
        try:
            result = test_func()
            results.append((name, result))
            status = "✅" if result else "❌"
            print(f"{status} {name}")
        except Exception as e:
            results.append((name, False))
            print(f"❌ {name}: {e}")
        print()
    
    # 汇总
    print("=" * 50)
    print("📊 测试汇总")
    passed = sum(1 for _, r in results if r)
    total = len(results)
    print(f"通过: {passed}/{total}")
    
    if passed == total:
        print("\n🎉 全部测试通过！SDK已就绪！")
    else:
        print("\n⚠️ 部分测试未通过，请检查")


if __name__ == "__main__":
    main()
