#!/usr/bin/env python3
"""
系统测试脚本
测试手部检测Web服务的各个组件
"""

import sys
import os
import time
import json

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

def test_import_modules():
    """测试模块导入"""
    print("🔍 测试模块导入...")
    try:
        import cv2
        print("✅ OpenCV 导入成功")
        
        import mediapipe as mp
        print("✅ MediaPipe 导入成功")
        
        import flask
        import flask_socketio
        print("✅ Flask 和 SocketIO 导入成功")
        
        from hand_detection_3d import load_mediapipe_model, process_frame_3d
        print("✅ 手部检测模块导入成功")
        
        from web_server import HandDetectionWebServer
        print("✅ Web服务器模块导入成功")
        
        from robot_client import RobotArmClient
        print("✅ 机械臂客户端模块导入成功")
        
        return True
    except Exception as e:
        print(f"❌ 模块导入失败: {e}")
        return False

def test_hand_detection():
    """测试手部检测功能"""
    print("\n🤖 测试手部检测功能...")
    try:
        from hand_detection_3d import load_mediapipe_model, process_frame_3d
        import numpy as np
        
        # 加载模型
        model = load_mediapipe_model()
        print("✅ MediaPipe模型加载成功")
        
        # 创建测试图像
        test_frame = np.zeros((480, 640, 3), dtype=np.uint8)
        test_frame[:] = (50, 50, 50)  # 灰色背景
        
        # 处理帧
        control_signal, hand_data = process_frame_3d(test_frame, model)
        
        # 检查输出格式
        required_keys = ['x_angle', 'y_angle', 'z_angle', 'grip', 'action', 'speed']
        if all(key in control_signal for key in required_keys):
            print("✅ 手部检测输出格式正确")
            print(f"   控制信号: {control_signal}")
            return True
        else:
            print("❌ 手部检测输出格式不正确")
            return False
            
    except Exception as e:
        print(f"❌ 手部检测测试失败: {e}")
        return False

def test_web_server():
    """测试Web服务器"""
    print("\n🌐 测试Web服务器...")
    try:
        from web_server import HandDetectionWebServer
        
        # 创建服务器实例
        server = HandDetectionWebServer(port=5003)
        print("✅ Web服务器创建成功")
        
        # 测试路由配置
        with server.app.test_client() as client:
            # 测试主页
            response = client.get('/')
            if response.status_code == 200:
                print("✅ 主页路由正常")
            else:
                print(f"❌ 主页路由失败: {response.status_code}")
                return False
            
            # 测试API状态
            response = client.get('/api/status')
            if response.status_code == 200:
                print("✅ API状态路由正常")
                status_data = json.loads(response.data)
                print(f"   状态信息: {status_data}")
            else:
                print(f"❌ API状态路由失败: {response.status_code}")
                return False
        
        return True
    except Exception as e:
        print(f"❌ Web服务器测试失败: {e}")
        return False

def test_robot_client():
    """测试机械臂客户端"""
    print("\n🦾 测试机械臂客户端...")
    try:
        from robot_client import RobotArmClient, MockRobotArmController
        
        # 创建模拟控制器
        mock_controller = MockRobotArmController()
        print("✅ 模拟机械臂控制器创建成功")
        
        # 测试控制器方法
        mock_controller.move_to_angles(45, 90, 135, 5)
        print("✅ 机械臂移动测试成功")
        
        mock_controller.set_gripper_state(1)
        print("✅ 抓取器控制测试成功")
        
        # 创建客户端（不连接服务器）
        client = RobotArmClient('http://localhost:5003')
        print("✅ 机械臂客户端创建成功")
        
        return True
    except Exception as e:
        print(f"❌ 机械臂客户端测试失败: {e}")
        return False

def test_file_structure():
    """测试文件结构"""
    print("\n📁 测试文件结构...")
    required_files = [
        'README.md',
        'requirements.txt',
        'run_web_service.py',
        'start_service.sh',
        'start_service.bat',
        'start_robot_client.sh',
        'start_robot_client.bat',
        'src/__init__.py',
        'src/hand_detection_3d.py',
        'src/web_server.py',
        'src/robot_client.py',
        'templates/index.html'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not os.path.exists(file_path):
            missing_files.append(file_path)
    
    if missing_files:
        print(f"❌ 缺少文件: {missing_files}")
        return False
    else:
        print("✅ 所有必需文件存在")
        return True

def main():
    """主测试函数"""
    print("=" * 60)
    print("🧪 手部检测Web服务系统测试")
    print("=" * 60)
    
    tests = [
        test_file_structure,
        test_import_modules,
        test_hand_detection,
        test_web_server,
        test_robot_client
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        if test():
            passed += 1
        else:
            print(f"\n⚠️  测试失败，请检查上述错误")
    
    print("\n" + "=" * 60)
    print(f"📊 测试结果: {passed}/{total} 个测试通过")
    
    if passed == total:
        print("🎉 所有测试通过！系统准备就绪")
        print("\n🚀 启动命令:")
        print("   Linux/Mac: ./start_service.sh")
        print("   Windows:   start_service.bat")
        print("   访问地址:  http://localhost:5000")
    else:
        print("❌ 部分测试失败，请修复问题后重试")
    
    print("=" * 60)
    return passed == total

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)