"""
平台适配器模块
负责处理不同平台的输入设备兼容性
"""

import platform
import time
from typing import Dict, Any, List, Optional
import threading

class PlatformAdapter:
    """
    平台适配器
    负责处理不同平台的输入设备兼容性
    """
    
    def __init__(self, plugin):
        """
        初始化平台适配器
        
        Args:
            plugin: 多平台输入支持插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 平台信息
        self.platform_info = {
            'system': platform.system(),
            'release': platform.release(),
            'version': platform.version(),
            'machine': platform.machine(),
            'processor': platform.processor(),
            'architecture': platform.architecture()[0]
        }
        
        # 平台配置
        self.platform_config = {
            'Windows': {
                'api_priority': ['directinput', 'xinput', 'rawinput'],
                'default_deadzone': 0.1,
                'max_devices': 16,
                'polling_rate': 120,
                'supported_features': ['xinput', 'directinput', 'hid']
            },
            'Linux': {
                'api_priority': ['evdev', 'x11', 'udev'],
                'default_deadzone': 0.15,
                'max_devices': 32,
                'polling_rate': 100,
                'supported_features': ['evdev', 'udev', 'x11']
            },
            'Darwin': {  # macOS
                'api_priority': ['iokit', 'coregraphics', 'hid'],
                'default_deadzone': 0.1,
                'max_devices': 16,
                'polling_rate': 120,
                'supported_features': ['iokit', 'coregraphics', 'hid']
            }
        }
        
        # 当前平台配置
        self.current_platform_config = self.platform_config.get(
            self.platform_info['system'], 
            {
                'api_priority': ['generic'],
                'default_deadzone': 0.1,
                'max_devices': 8,
                'polling_rate': 60,
                'supported_features': ['generic']
            }
        )
        
        # 设备适配器
        self.device_adapters = {}
        
        # 平台特定功能
        self.platform_features = {
            'has_vibration': False,
            'has_motion': False,
            'has_touch': False,
            'has_gesture': False,
            'max_touch_points': 0
        }
        
        # API支持状态
        self.api_support = {}
        
        # 统计信息
        self.adapter_stats = {
            'devices_adapted': 0,
            'api_loaded': 0,
            'api_errors': 0,
            'compatibility_fixes': 0,
            'data_translated': 0
        }
        
        # 线程管理
        self.adapter_thread = None
        self.running = False
        
        # 时间戳记录
        self.last_api_check = 0.0
        self.last_compatibility_check = 0.0
        
        print(f"✓ 平台适配器已创建 ({self.platform_info['system']})")
        
    def initialize(self) -> bool:
        """
        初始化平台适配器
        
        Returns:
            是否初始化成功
        """
        try:
            # 检测平台特定功能
            self._detect_platform_features()
            
            # 加载平台API
            self._load_platform_apis()
            
            # 创建设备适配器
            self._create_device_adapters()
            
            self.initialized = True
            print("✓ 平台适配器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 平台适配器初始化失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def enable(self) -> bool:
        """
        启用平台适配器
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 平台适配器未初始化")
                return False
                
            self.enabled = True
            self.running = True
            
            # 启动适配器线程
            self.adapter_thread = threading.Thread(target=self._adapter_update_loop, daemon=True)
            self.adapter_thread.start()
            
            print("✓ 平台适配器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 平台适配器启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用平台适配器"""
        try:
            self.enabled = False
            self.running = False
            
            # 等待适配器线程结束
            if self.adapter_thread and self.adapter_thread.is_alive():
                self.adapter_thread.join(timeout=2.0)
                
            # 清理平台API
            self._cleanup_platform_apis()
            
            print("✓ 平台适配器已禁用")
            
        except Exception as e:
            print(f"✗ 平台适配器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理平台适配器资源"""
        try:
            self.disable()
            self.device_adapters.clear()
            self.api_support.clear()
            self.initialized = False
            print("✓ 平台适配器资源已清理")
            
        except Exception as e:
            print(f"✗ 平台适配器资源清理失败: {e}")
            import traceback
            traceback.print_exc()
            
    def update(self, dt: float):
        """
        更新平台适配器状态
        
        Args:
            dt: 时间增量
        """
        try:
            if not self.enabled:
                return
                
            # 定期检查API支持状态
            self._check_api_support()
            
        except Exception as e:
            print(f"✗ 平台适配器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _adapter_update_loop(self):
        """适配器更新循环"""
        try:
            # 更新间隔基于平台轮询率
            update_interval = 1.0 / self.current_platform_config['polling_rate']
            
            while self.running:
                if self.enabled:
                    self._update_device_adapters()
                    
                time.sleep(update_interval)
                
        except Exception as e:
            print(f"✗ 适配器更新循环失败: {e}")
            
    def _detect_platform_features(self):
        """检测平台特定功能"""
        try:
            system = self.platform_info['system']
            
            if system == 'Windows':
                self.platform_features['has_vibration'] = True
                self.platform_features['has_motion'] = True
                self.platform_features['has_touch'] = True
                self.platform_features['max_touch_points'] = 10
                
            elif system == 'Linux':
                self.platform_features['has_vibration'] = True
                self.platform_features['has_motion'] = True
                self.platform_features['has_touch'] = True
                self.platform_features['max_touch_points'] = 10
                
            elif system == 'Darwin':  # macOS
                self.platform_features['has_vibration'] = True
                self.platform_features['has_motion'] = True
                self.platform_features['has_touch'] = True
                self.platform_features['max_touch_points'] = 5
                
            print(f"✓ 平台功能检测完成: {self.platform_features}")
            
        except Exception as e:
            print(f"✗ 平台功能检测失败: {e}")
            
    def _load_platform_apis(self):
        """加载平台API"""
        try:
            system = self.platform_info['system']
            api_priority = self.current_platform_config['api_priority']
            
            for api_name in api_priority:
                try:
                    if self._load_api(api_name):
                        self.api_support[api_name] = True
                        self.adapter_stats['api_loaded'] += 1
                        print(f"✓ 平台API已加载: {api_name}")
                    else:
                        self.api_support[api_name] = False
                except Exception as e:
                    self.api_support[api_name] = False
                    self.adapter_stats['api_errors'] += 1
                    print(f"✗ 平台API加载失败: {api_name} - {e}")
                    
        except Exception as e:
            print(f"✗ 平台API加载失败: {e}")
            
    def _load_api(self, api_name: str) -> bool:
        """
        加载特定API
        
        Args:
            api_name: API名称
            
        Returns:
            是否加载成功
        """
        try:
            system = self.platform_info['system']
            
            # 这里应该实现实际的API加载逻辑
            # 由于是模拟实现，我们只是记录支持状态
            
            if system == 'Windows' and api_name in ['directinput', 'xinput', 'rawinput']:
                return True
            elif system == 'Linux' and api_name in ['evdev', 'x11', 'udev']:
                return True
            elif system == 'Darwin' and api_name in ['iokit', 'coregraphics', 'hid']:
                return True
            else:
                return False
                
        except Exception as e:
            print(f"✗ API加载失败: {api_name} - {e}")
            return False
            
    def _cleanup_platform_apis(self):
        """清理平台API"""
        try:
            # 这里应该实现实际的API清理逻辑
            self.api_support.clear()
            print("✓ 平台API已清理")
        except Exception as e:
            print(f"✗ 平台API清理失败: {e}")
            
    def _create_device_adapters(self):
        """创建设备适配器"""
        try:
            # 这里应该为不同类型的设备创建适配器
            # 由于是模拟实现，我们只是初始化适配器字典
            self.device_adapters = {
                'keyboard': None,
                'mouse': None,
                'gamepad': None,
                'touch': None,
                'vr_controller': None,
                'motion_sensor': None
            }
            
            print("✓ 设备适配器创建完成")
        except Exception as e:
            print(f"✗ 设备适配器创建失败: {e}")
            
    def _update_device_adapters(self):
        """更新设备适配器"""
        try:
            # 这里应该实现设备适配器的更新逻辑
            pass
        except Exception as e:
            print(f"✗ 设备适配器更新失败: {e}")
            
    def _check_api_support(self):
        """检查API支持状态"""
        try:
            current_time = time.time()
            
            # 每30秒检查一次API支持
            if current_time - self.last_api_check >= 30.0:
                for api_name in list(self.api_support.keys()):
                    # 重新检查API支持状态
                    try:
                        # 这里应该实现实际的API支持检查逻辑
                        pass
                    except Exception:
                        pass
                        
                self.last_api_check = current_time
                
        except Exception as e:
            print(f"✗ API支持检查失败: {e}")
            
    def adapt_device_data(self, device_type: str, raw_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        适配设备数据
        
        Args:
            device_type: 设备类型
            raw_data: 原始设备数据
            
        Returns:
            适配后的设备数据
        """
        try:
            # 根据设备类型和平台进行数据适配
            adapted_data = raw_data.copy()
            
            # 应用死区处理
            deadzone = self.current_platform_config['default_deadzone']
            if 'axes' in adapted_data:
                for axis_name, axis_value in adapted_data['axes'].items():
                    if abs(axis_value) < deadzone:
                        adapted_data['axes'][axis_name] = 0.0
                        
            # 应用平台特定的转换
            system = self.platform_info['system']
            if system == 'Windows':
                adapted_data = self._adapt_windows_data(device_type, adapted_data)
            elif system == 'Linux':
                adapted_data = self._adapt_linux_data(device_type, adapted_data)
            elif system == 'Darwin':
                adapted_data = self._adapt_macos_data(device_type, adapted_data)
                
            self.adapter_stats['data_translated'] += 1
            return adapted_data
            
        except Exception as e:
            print(f"✗ 设备数据适配失败: {e}")
            return raw_data
            
    def _adapt_windows_data(self, device_type: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        适配Windows平台数据
        
        Args:
            device_type: 设备类型
            data: 设备数据
            
        Returns:
            适配后的数据
        """
        try:
            # Windows平台特定的数据适配
            adapted_data = data.copy()
            
            # 例如：调整坐标系、按键映射等
            if device_type == 'mouse':
                # Windows鼠标坐标可能需要调整
                pass
            elif device_type == 'gamepad':
                # XInput控制器数据适配
                pass
                
            return adapted_data
        except Exception as e:
            print(f"✗ Windows数据适配失败: {e}")
            return data
            
    def _adapt_linux_data(self, device_type: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        适配Linux平台数据
        
        Args:
            device_type: 设备类型
            data: 设备数据
            
        Returns:
            适配后的数据
        """
        try:
            # Linux平台特定的数据适配
            adapted_data = data.copy()
            
            # 例如：evdev事件处理、设备路径解析等
            return adapted_data
        except Exception as e:
            print(f"✗ Linux数据适配失败: {e}")
            return data
            
    def _adapt_macos_data(self, device_type: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        适配macOS平台数据
        
        Args:
            device_type: 设备类型
            data: 设备数据
            
        Returns:
            适配后的数据
        """
        try:
            # macOS平台特定的数据适配
            adapted_data = data.copy()
            
            # 例如：CoreGraphics事件处理、HID设备解析等
            return adapted_data
        except Exception as e:
            print(f"✗ macOS数据适配失败: {e}")
            return data
            
    def get_platform_info(self) -> Dict[str, Any]:
        """
        获取平台信息
        
        Returns:
            平台信息字典
        """
        return self.platform_info.copy()
        
    def get_platform_config(self) -> Dict[str, Any]:
        """
        获取当前平台配置
        
        Returns:
            平台配置字典
        """
        return self.current_platform_config.copy()
        
    def get_platform_features(self) -> Dict[str, Any]:
        """
        获取平台功能
        
        Returns:
            平台功能字典
        """
        return self.platform_features.copy()
        
    def is_api_supported(self, api_name: str) -> bool:
        """
        检查API是否支持
        
        Args:
            api_name: API名称
            
        Returns:
            是否支持
        """
        return self.api_support.get(api_name, False)
        
    def get_supported_apis(self) -> List[str]:
        """
        获取支持的API列表
        
        Returns:
            支持的API列表
        """
        return [api for api, supported in self.api_support.items() if supported]
        
    def apply_compatibility_fix(self, device_id: int, issue_type: str) -> bool:
        """
        应用兼容性修复
        
        Args:
            device_id: 设备ID
            issue_type: 问题类型
            
        Returns:
            是否应用成功
        """
        try:
            # 这里应该实现具体的兼容性修复逻辑
            self.adapter_stats['compatibility_fixes'] += 1
            print(f"✓ 兼容性修复已应用: 设备 {device_id}, 问题 {issue_type}")
            return True
        except Exception as e:
            print(f"✗ 兼容性修复应用失败: {e}")
            return False
            
    def get_adapter_stats(self) -> Dict[str, int]:
        """
        获取适配器统计信息
        
        Returns:
            适配器统计字典
        """
        return self.adapter_stats.copy()
        
    def reset_adapter_stats(self):
        """重置适配器统计信息"""
        try:
            self.adapter_stats = {
                'devices_adapted': 0,
                'api_loaded': 0,
                'api_errors': 0,
                'compatibility_fixes': 0,
                'data_translated': 0
            }
            print("✓ 适配器统计信息已重置")
        except Exception as e:
            print(f"✗ 适配器统计信息重置失败: {e}")
            
    def set_platform_config(self, config: Dict[str, Any]) -> bool:
        """
        设置平台配置
        
        Args:
            config: 平台配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.current_platform_config.update(config)
            print(f"✓ 平台配置已更新: {self.current_platform_config}")
            return True
        except Exception as e:
            print(f"✗ 平台配置设置失败: {e}")
            return False
            
    def get_device_adapter(self, device_type: str) -> Optional[Any]:
        """
        获取设备适配器
        
        Args:
            device_type: 设备类型
            
        Returns:
            设备适配器或None
        """
        return self.device_adapters.get(device_type)
        
    def register_device_adapter(self, device_type: str, adapter: Any) -> bool:
        """
        注册设备适配器
        
        Args:
            device_type: 设备类型
            adapter: 设备适配器
            
        Returns:
            是否注册成功
        """
        try:
            self.device_adapters[device_type] = adapter
            print(f"✓ 设备适配器已注册: {device_type}")
            return True
        except Exception as e:
            print(f"✗ 设备适配器注册失败: {e}")
            return False
            
    def get_system_architecture(self) -> str:
        """
        获取系统架构
        
        Returns:
            系统架构字符串
        """
        return self.platform_info['architecture']
        
    def is_64bit_system(self) -> bool:
        """
        检查是否为64位系统
        
        Returns:
            是否为64位系统
        """
        return '64' in self.platform_info['architecture']
        
    def get_system_processor(self) -> str:
        """
        获取系统处理器信息
        
        Returns:
            处理器信息字符串
        """
        return self.platform_info['processor']