"""基础连接测试"""

import asyncio
import sys
import os
from pathlib import Path
import pytest

# 添加 src 目录到 Python 路径
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from novnc_client import NoVNCClient
from novnc_client.exceptions import ConnectionError


@pytest.mark.asyncio
async def test_basic_connection():
    """测试基础连接功能"""
    print("开始测试基础连接...")

    try:
        async with NoVNCClient("localhost", 6080) as client:
            print("[OK] 连接成功")

            # 获取服务器信息
            server_info = client.server_info
            if server_info:
                print(f"[OK] 服务器信息: {server_info.width}x{server_info.height}")
                print(f"[OK] 服务器名称: {server_info.server_name}")
                print(f"[OK] 像素格式: {server_info.pixel_format.bits_per_pixel} 位")

            # 测试屏幕尺寸
            width, height = client.screen_size
            print(f"[OK] 屏幕尺寸: {width}x{height}")

            return True

    except ConnectionError as e:
        print(f"[ERROR] 连接失败: {e}")
        return False
    except Exception as e:
        print(f"[ERROR] 未知错误: {e}")
        import traceback

        traceback.print_exc()
        return False


@pytest.mark.asyncio
async def test_screenshot():
    """测试截图功能"""
    print("\n开始测试截图功能...")

    try:
        async with NoVNCClient("localhost", 6080) as client:
            # 截图
            screenshot_path = "test_screenshot.png"
            image = await client.take_screenshot(screenshot_path)

            if os.path.exists(screenshot_path):
                print(f"[OK] 截图成功: {screenshot_path}")
                print(f"[OK] 图像尺寸: {image.width}x{image.height}")
                print(f"[OK] 图像模式: {image.mode}")

                # 清理测试文件
                os.remove(screenshot_path)
                return True
            else:
                print("[ERROR] 截图文件未创建")
                return False

    except Exception as e:
        print(f"[ERROR] 截图失败: {e}")
        import traceback

        traceback.print_exc()
        return False


@pytest.mark.asyncio
async def test_mouse_operations():
    """测试鼠标操作"""
    print("\n开始测试鼠标操作...")

    try:
        async with NoVNCClient("localhost", 6080) as client:
            # 鼠标移动
            await client.mouse_move(100, 100)
            print("[OK] 鼠标移动成功")

            # 鼠标点击
            await client.mouse_click(100, 100, "left")
            print("[OK] 鼠标点击成功")

            # 鼠标滚轮
            await client.mouse_scroll(200, 200, "up", steps=1)
            print("[OK] 鼠标滚轮成功")

            return True

    except Exception as e:
        print(f"[ERROR] 鼠标操作失败: {e}")
        import traceback

        traceback.print_exc()
        return False


async def main():
    """主测试函数"""
    print("=== noVNC 客户端基础功能测试 ===\n")

    # 测试基础连接
    connection_ok = await test_basic_connection()

    if connection_ok:
        # 测试截图
        screenshot_ok = await test_screenshot()

        # 测试鼠标操作
        mouse_ok = await test_mouse_operations()

        print("\n=== 测试结果 ===")
        print(f"连接测试: {'[OK] 通过' if connection_ok else '[ERROR] 失败'}")
        print(f"截图测试: {'[OK] 通过' if screenshot_ok else '[ERROR] 失败'}")
        print(f"鼠标测试: {'[OK] 通过' if mouse_ok else '[ERROR] 失败'}")

        if all([connection_ok, screenshot_ok, mouse_ok]):
            print("\n[SUCCESS] 所有测试通过！")
            return True
        else:
            print("\n[WARNING] 部分测试失败")
            return False
    else:
        print("\n[ERROR] 连接失败，跳过后续测试")
        return False


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
