"""
配置管理器模块
负责管理多平台输入插件的配置和用户偏好设置
"""

import json
import os
from typing import Dict, Any, List, Optional
from enum import Enum
import time

class ConfigType(Enum):
    """配置类型枚举"""
    INPUT = "input"
    DEVICE = "device"
    GESTURE = "gesture"
    HAPTIC = "haptic"
    MAPPING = "mapping"
    USER_PREFERENCES = "user_preferences"

class ConfigManager:
    """
    配置管理器
    负责管理多平台输入插件的配置和用户偏好设置
    """
    
    def __init__(self, plugin):
        """
        初始化配置管理器
        
        Args:
            plugin: 多平台输入支持插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 配置路径
        self.config_paths = {
            'base_path': './config/multiplatform_input',
            'input_config': './config/multiplatform_input/input_config.json',
            'device_config': './config/multiplatform_input/device_config.json',
            'gesture_config': './config/multiplatform_input/gesture_config.json',
            'haptic_config': './config/multiplatform_input/haptic_config.json',
            'mapping_config': './config/multiplatform_input/mapping_config.json',
            'user_preferences': './config/multiplatform_input/user_preferences.json'
        }
        
        # 配置数据
        self.config_data = {
            ConfigType.INPUT: {},
            ConfigType.DEVICE: {},
            ConfigType.GESTURE: {},
            ConfigType.HAPTIC: {},
            ConfigType.MAPPING: {},
            ConfigType.USER_PREFERENCES: {}
        }
        
        # 默认配置
        self.default_configs = {
            ConfigType.INPUT: {
                'polling_rate': 120,
                'deadzone': 0.1,
                'double_click_time': 0.3,
                'long_press_time': 0.5,
                'swipe_threshold': 50,
                'gesture_timeout': 1.0
            },
            ConfigType.DEVICE: {
                'auto_discovery': True,
                'discovery_interval': 5.0,
                'supported_platforms': ['Windows', 'Linux', 'Darwin']
            },
            ConfigType.GESTURE: {
                'tap_max_duration': 0.3,
                'tap_max_distance': 20.0,
                'double_tap_timeout': 0.3,
                'long_press_duration': 0.5,
                'swipe_min_distance': 50.0,
                'swipe_max_duration': 0.5,
                'pinch_threshold': 20.0,
                'rotate_threshold': 10.0
            },
            ConfigType.HAPTIC: {
                'default_intensity': 0.5,
                'default_duration': 0.2,
                'max_intensity': 1.0,
                'min_duration': 0.01,
                'max_duration': 5.0,
                'update_rate': 60.0
            },
            ConfigType.MAPPING: {
                'enable_mapping': True,
                'enable_combinations': True,
                'enable_sequences': True,
                'combination_timeout': 0.5,
                'sequence_timeout': 1.0
            },
            ConfigType.USER_PREFERENCES: {
                'language': 'zh-CN',
                'theme': 'dark',
                'enable_notifications': True,
                'auto_save_config': True,
                'config_backup_count': 5
            }
        }
        
        # 配置版本
        self.config_version = "1.0.0"
        
        # 配置变更监听器
        self.config_listeners = {}
        
        # 统计信息
        self.config_stats = {
            'configs_loaded': 0,
            'configs_saved': 0,
            'configs_changed': 0,
            'backup_created': 0,
            'load_errors': 0,
            'save_errors': 0
        }
        
        # 时间戳记录
        self.last_config_change = {}
        self.config_load_time = {}
        
        print("✓ 配置管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化配置管理器
        
        Returns:
            是否初始化成功
        """
        try:
            # 创建配置目录
            self._create_config_directories()
            
            # 加载所有配置
            self._load_all_configs()
            
            # 应用默认配置（如果配置不存在）
            self._apply_default_configs()
            
            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
            print("✓ 配置管理器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 配置管理器启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用配置管理器"""
        try:
            self.enabled = False
            
            # 自动保存配置（如果启用）
            if self.get_config(ConfigType.USER_PREFERENCES, 'auto_save_config', True):
                self.save_all_configs()
                
            print("✓ 配置管理器已禁用")
            
        except Exception as e:
            print(f"✗ 配置管理器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理配置管理器资源"""
        try:
            self.disable()
            self.config_data.clear()
            self.default_configs.clear()
            self.config_listeners.clear()
            self.last_config_change.clear()
            self.config_load_time.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
                
            # 定期自动保存配置（如果启用）
            # 这里可以实现定期保存逻辑
            pass
            
        except Exception as e:
            print(f"✗ 配置管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _create_config_directories(self):
        """创建配置目录"""
        try:
            base_path = self.config_paths['base_path']
            if not os.path.exists(base_path):
                os.makedirs(base_path)
                print(f"✓ 配置目录已创建: {base_path}")
        except Exception as e:
            print(f"✗ 配置目录创建失败: {e}")
            
    def _load_all_configs(self):
        """加载所有配置"""
        try:
            for config_type in ConfigType:
                self._load_config(config_type)
                
            print("✓ 所有配置加载完成")
        except Exception as e:
            print(f"✗ 配置加载失败: {e}")
            
    def _load_config(self, config_type: ConfigType):
        """
        加载指定类型的配置
        
        Args:
            config_type: 配置类型
        """
        try:
            config_file = self.config_paths[config_type.value + '_config']
            
            if os.path.exists(config_file):
                with open(config_file, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                    
                self.config_data[config_type] = config_data
                self.config_load_time[config_type.value] = time.time()
                self.config_stats['configs_loaded'] += 1
                
                print(f"✓ 配置已加载: {config_type.value}")
            else:
                print(f"⚠ 配置文件不存在: {config_file}")
                
        except Exception as e:
            print(f"✗ 配置加载失败 {config_type.value}: {e}")
            self.config_stats['load_errors'] += 1
            
    def _apply_default_configs(self):
        """应用默认配置"""
        try:
            for config_type, default_config in self.default_configs.items():
                if not self.config_data[config_type]:
                    self.config_data[config_type] = default_config.copy()
                    print(f"✓ 默认配置已应用: {config_type.value}")
                    
        except Exception as e:
            print(f"✗ 默认配置应用失败: {e}")
            
    def save_all_configs(self) -> bool:
        """
        保存所有配置
        
        Returns:
            是否保存成功
        """
        try:
            success = True
            for config_type in ConfigType:
                if not self._save_config(config_type):
                    success = False
                    
            if success:
                print("✓ 所有配置保存完成")
            return success
            
        except Exception as e:
            print(f"✗ 配置保存失败: {e}")
            self.config_stats['save_errors'] += 1
            return False
            
    def _save_config(self, config_type: ConfigType) -> bool:
        """
        保存指定类型的配置
        
        Args:
            config_type: 配置类型
            
        Returns:
            是否保存成功
        """
        try:
            config_file = self.config_paths[config_type.value + '_config']
            
            # 创建备份（如果启用）
            if self.get_config(ConfigType.USER_PREFERENCES, 'auto_backup_config', False):
                self._create_backup(config_file)
                
            # 保存配置
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config_data[config_type], f, ensure_ascii=False, indent=2)
                
            self.config_stats['configs_saved'] += 1
            print(f"✓ 配置已保存: {config_type.value}")
            return True
            
        except Exception as e:
            print(f"✗ 配置保存失败 {config_type.value}: {e}")
            self.config_stats['save_errors'] += 1
            return False
            
    def _create_backup(self, config_file: str):
        """
        创建配置备份
        
        Args:
            config_file: 配置文件路径
        """
        try:
            if not os.path.exists(config_file):
                return
                
            backup_count = self.get_config(ConfigType.USER_PREFERENCES, 'config_backup_count', 5)
            
            # 创建备份文件名
            base_name = os.path.splitext(config_file)[0]
            backup_file = f"{base_name}.backup.{int(time.time())}.json"
            
            # 复制文件
            with open(config_file, 'r', encoding='utf-8') as src:
                with open(backup_file, 'w', encoding='utf-8') as dst:
                    dst.write(src.read())
                    
            self.config_stats['backup_created'] += 1
            print(f"✓ 配置备份已创建: {backup_file}")
            
            # 清理旧备份
            self._cleanup_old_backups(config_file, backup_count)
            
        except Exception as e:
            print(f"✗ 配置备份创建失败: {e}")
            
    def _cleanup_old_backups(self, config_file: str, max_backups: int):
        """
        清理旧备份
        
        Args:
            config_file: 配置文件路径
            max_backups: 最大备份数量
        """
        try:
            base_name = os.path.splitext(config_file)[0]
            backup_pattern = f"{base_name}.backup."
            
            # 查找备份文件
            backup_files = []
            config_dir = os.path.dirname(config_file)
            if os.path.exists(config_dir):
                for file in os.listdir(config_dir):
                    if file.startswith(backup_pattern) and file.endswith('.json'):
                        file_path = os.path.join(config_dir, file)
                        backup_files.append((file_path, os.path.getmtime(file_path)))
                        
            # 按时间排序
            backup_files.sort(key=lambda x: x[1], reverse=True)
            
            # 删除多余的备份
            for file_path, _ in backup_files[max_backups:]:
                try:
                    os.remove(file_path)
                    print(f"✓ 旧备份已删除: {file_path}")
                except Exception as e:
                    print(f"✗ 旧备份删除失败: {file_path} - {e}")
                    
        except Exception as e:
            print(f"✗ 旧备份清理失败: {e}")
            
    def get_config(self, config_type: ConfigType, key: str, default_value: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            config_type: 配置类型
            key: 配置键
            default_value: 默认值
            
        Returns:
            配置值
        """
        try:
            config_section = self.config_data.get(config_type, {})
            return config_section.get(key, default_value)
        except Exception as e:
            print(f"✗ 配置获取失败: {config_type.value}.{key} - {e}")
            return default_value
            
    def set_config(self, config_type: ConfigType, key: str, value: Any) -> bool:
        """
        设置配置值
        
        Args:
            config_type: 配置类型
            key: 配置键
            value: 配置值
            
        Returns:
            是否设置成功
        """
        try:
            if config_type not in self.config_data:
                self.config_data[config_type] = {}
                
            old_value = self.config_data[config_type].get(key)
            self.config_data[config_type][key] = value
            self.last_config_change[config_type.value] = time.time()
            self.config_stats['configs_changed'] += 1
            
            # 触发配置变更监听器
            self._trigger_config_listener(config_type, key, old_value, value)
            
            print(f"✓ 配置已设置: {config_type.value}.{key} = {value}")
            return True
            
        except Exception as e:
            print(f"✗ 配置设置失败: {config_type.value}.{key} - {e}")
            return False
            
    def get_config_section(self, config_type: ConfigType) -> Dict[str, Any]:
        """
        获取配置节
        
        Args:
            config_type: 配置类型
            
        Returns:
            配置节字典
        """
        return self.config_data.get(config_type, {}).copy()
        
    def set_config_section(self, config_type: ConfigType, config_section: Dict[str, Any]) -> bool:
        """
        设置配置节
        
        Args:
            config_type: 配置类型
            config_section: 配置节字典
            
        Returns:
            是否设置成功
        """
        try:
            self.config_data[config_type] = config_section.copy()
            self.last_config_change[config_type.value] = time.time()
            self.config_stats['configs_changed'] += 1
            
            print(f"✓ 配置节已设置: {config_type.value}")
            return True
            
        except Exception as e:
            print(f"✗ 配置节设置失败: {config_type.value} - {e}")
            return False
            
    def reset_config(self, config_type: ConfigType) -> bool:
        """
        重置配置为默认值
        
        Args:
            config_type: 配置类型
            
        Returns:
            是否重置成功
        """
        try:
            if config_type in self.default_configs:
                self.config_data[config_type] = self.default_configs[config_type].copy()
                self.last_config_change[config_type.value] = time.time()
                self.config_stats['configs_changed'] += 1
                
                print(f"✓ 配置已重置: {config_type.value}")
                return True
            else:
                print(f"✗ 无默认配置: {config_type.value}")
                return False
                
        except Exception as e:
            print(f"✗ 配置重置失败: {config_type.value} - {e}")
            return False
            
    def register_config_listener(self, config_type: ConfigType, key: str, listener: callable):
        """
        注册配置变更监听器
        
        Args:
            config_type: 配置类型
            key: 配置键
            listener: 监听器回调函数
        """
        try:
            listener_key = f"{config_type.value}.{key}"
            if listener_key not in self.config_listeners:
                self.config_listeners[listener_key] = []
            self.config_listeners[listener_key].append(listener)
            print(f"✓ 配置监听器已注册: {listener_key}")
        except Exception as e:
            print(f"✗ 配置监听器注册失败: {e}")
            
    def unregister_config_listener(self, config_type: ConfigType, key: str, listener: callable):
        """
        注销配置变更监听器
        
        Args:
            config_type: 配置类型
            key: 配置键
            listener: 监听器回调函数
        """
        try:
            listener_key = f"{config_type.value}.{key}"
            if listener_key in self.config_listeners:
                if listener in self.config_listeners[listener_key]:
                    self.config_listeners[listener_key].remove(listener)
                    print(f"✓ 配置监听器已注销: {listener_key}")
        except Exception as e:
            print(f"✗ 配置监听器注销失败: {e}")
            
    def _trigger_config_listener(self, config_type: ConfigType, key: str, old_value: Any, new_value: Any):
        """
        触发配置变更监听器
        
        Args:
            config_type: 配置类型
            key: 配置键
            old_value: 旧值
            new_value: 新值
        """
        try:
            listener_key = f"{config_type.value}.{key}"
            if listener_key in self.config_listeners:
                for listener in self.config_listeners[listener_key]:
                    try:
                        listener(key, old_value, new_value)
                    except Exception as e:
                        print(f"✗ 配置监听器执行失败: {e}")
        except Exception as e:
            print(f"✗ 配置监听器触发失败: {e}")
            
    def export_config(self, config_type: ConfigType, file_path: str) -> bool:
        """
        导出配置
        
        Args:
            config_type: 配置类型
            file_path: 导出文件路径
            
        Returns:
            是否导出成功
        """
        try:
            config_data = self.config_data.get(config_type, {})
            
            # 添加元数据
            export_data = {
                'config_type': config_type.value,
                'version': self.config_version,
                'export_time': time.time(),
                'data': config_data
            }
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, ensure_ascii=False, indent=2)
                
            print(f"✓ 配置已导出: {file_path}")
            return True
            
        except Exception as e:
            print(f"✗ 配置导出失败: {e}")
            return False
            
    def import_config(self, file_path: str) -> bool:
        """
        导入配置
        
        Args:
            file_path: 导入文件路径
            
        Returns:
            是否导入成功
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                import_data = json.load(f)
                
            config_type = ConfigType(import_data['config_type'])
            config_data = import_data['data']
            
            self.config_data[config_type] = config_data
            self.last_config_change[config_type.value] = time.time()
            self.config_stats['configs_changed'] += 1
            
            print(f"✓ 配置已导入: {file_path}")
            return True
            
        except Exception as e:
            print(f"✗ 配置导入失败: {e}")
            return False
            
    def get_config_stats(self) -> Dict[str, Any]:
        """
        获取配置统计信息
        
        Returns:
            配置统计字典
        """
        return self.config_stats.copy()
        
    def reset_config_stats(self):
        """重置配置统计信息"""
        try:
            self.config_stats = {
                'configs_loaded': sum(1 for ct in ConfigType if self.config_data[ct]),
                'configs_saved': 0,
                'configs_changed': 0,
                'backup_created': 0,
                'load_errors': 0,
                'save_errors': 0
            }
            print("✓ 配置统计信息已重置")
        except Exception as e:
            print(f"✗ 配置统计信息重置失败: {e}")
            
    def get_config_load_time(self, config_type: ConfigType) -> float:
        """
        获取配置加载时间
        
        Args:
            config_type: 配置类型
            
        Returns:
            加载时间戳
        """
        return self.config_load_time.get(config_type.value, 0.0)
        
    def get_last_config_change(self, config_type: ConfigType) -> float:
        """
        获取最后配置变更时间
        
        Args:
            config_type: 配置类型
            
        Returns:
            变更时间戳
        """
        return self.last_config_change.get(config_type.value, 0.0)
        
    def validate_config(self, config_type: ConfigType) -> bool:
        """
        验证配置有效性
        
        Args:
            config_type: 配置类型
            
        Returns:
            是否有效
        """
        try:
            # 这里可以实现配置验证逻辑
            # 例如：检查必需字段、值范围等
            config_data = self.config_data.get(config_type, {})
            
            # 基本验证：确保是字典类型
            if not isinstance(config_data, dict):
                print(f"✗ 配置验证失败: {config_type.value} 不是字典类型")
                return False
                
            print(f"✓ 配置验证通过: {config_type.value}")
            return True
            
        except Exception as e:
            print(f"✗ 配置验证失败: {config_type.value} - {e}")
            return False
            
    def migrate_config(self, old_version: str, new_version: str) -> bool:
        """
        迁移配置版本
        
        Args:
            old_version: 旧版本
            new_version: 新版本
            
        Returns:
            是否迁移成功
        """
        try:
            # 这里可以实现配置版本迁移逻辑
            # 根据版本差异调整配置结构
            print(f"✓ 配置版本迁移: {old_version} -> {new_version}")
            return True
            
        except Exception as e:
            print(f"✗ 配置版本迁移失败: {e}")
            return False

