"""
高级输入处理器模块
用于处理复杂的输入组合和上下文感知输入
"""

import time
from typing import Dict, Any, List, Optional, Callable, Set
import threading
from enum import Enum

class InputContext(Enum):
    """输入上下文枚举"""
    GLOBAL = "global"
    MENU = "menu"
    GAMEPLAY = "gameplay"
    CUTSCENE = "cutscene"
    PAUSE = "pause"
    INVENTORY = "inventory"
    DIALOG = "dialog"
    CUSTOM = "custom"

class AdvancedInputProcessor:
    """
    高级输入处理器
    用于处理复杂的输入组合和上下文感知输入
    """
    
    def __init__(self, plugin):
        """
        初始化高级输入处理器
        
        Args:
            plugin: 多平台输入支持插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 上下文管理
        self.input_contexts = {
            InputContext.GLOBAL: {'priority': 0, 'active': True},
            InputContext.MENU: {'priority': 10, 'active': False},
            InputContext.GAMEPLAY: {'priority': 5, 'active': False},
            InputContext.CUTSCENE: {'priority': 15, 'active': False},
            InputContext.PAUSE: {'priority': 20, 'active': False},
            InputContext.INVENTORY: {'priority': 8, 'active': False},
            InputContext.DIALOG: {'priority': 12, 'active': False}
        }
        
        self.current_context = InputContext.GLOBAL
        self.context_stack = [InputContext.GLOBAL]
        
        # 复杂输入模式
        self.input_patterns = {}
        self.pattern_counter = 0
        
        # 输入序列
        self.input_sequences = {}
        self.sequence_counter = 0
        
        # 输入修饰符
        self.active_modifiers = set()
        self.modifier_config = {
            'shift': ['shift', 'left_shift', 'right_shift'],
            'ctrl': ['ctrl', 'left_ctrl', 'right_ctrl', 'control'],
            'alt': ['alt', 'left_alt', 'right_alt'],
            'meta': ['meta', 'windows', 'cmd', 'super']
        }
        
        # 时间相关输入
        self.timed_inputs = {}
        self.chord_inputs = {}
        self.chord_counter = 0
        
        # 回调函数
        self.advanced_callbacks = {
            'context_changed': [],
            'pattern_matched': [],
            'sequence_completed': [],
            'modifier_changed': [],
            'timed_input': []
        }
        
        # 统计信息
        self.advanced_stats = {
            'contexts_switched': 0,
            'patterns_matched': 0,
            'sequences_completed': 0,
            'modifiers_activated': 0,
            'timed_inputs_processed': 0
        }
        
        # 配置
        self.advanced_config = {
            'pattern_timeout': 2.0,  # 模式匹配超时时间(秒)
            'sequence_timeout': 5.0,  # 序列超时时间(秒)
            'chord_timeout': 0.5,     # 和弦超时时间(秒)
            'double_press_time': 0.3, # 双击时间阈值(秒)
            'long_press_time': 0.5    # 长按时间阈值(秒)
        }
        
        # 时间戳记录
        self.last_input_time = {}
        self.pattern_start_time = {}
        self.sequence_start_time = {}
        
        print("✓ 高级输入处理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化高级输入处理器
        
        Returns:
            是否初始化成功
        """
        try:
            # 创建默认输入模式
            self._create_default_patterns()
            
            # 创建默认输入序列
            self._create_default_sequences()
            
            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
            print("✓ 高级输入处理器已禁用")
            
        except Exception as e:
            print(f"✗ 高级输入处理器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理高级输入处理器资源"""
        try:
            self.disable()
            self.input_patterns.clear()
            self.input_sequences.clear()
            self.timed_inputs.clear()
            self.chord_inputs.clear()
            self.advanced_callbacks.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
                
            # 检查超时的模式和序列
            self._check_pattern_timeouts()
            self._check_sequence_timeouts()
            self._check_chord_timeouts()
            
        except Exception as e:
            print(f"✗ 高级输入处理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _create_default_patterns(self):
        """创建默认输入模式"""
        try:
            # Konami Code 示例
            self.create_input_pattern(
                name="konami_code",
                inputs=['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'],
                context=InputContext.GLOBAL,
                description="Konami Code (↑↑↓↓←→←→BA)"
            )
            
            # 快速三连击示例
            self.create_input_pattern(
                name="quick_triple",
                inputs=['action', 'action', 'action'],
                context=InputContext.GAMEPLAY,
                description="快速三连击",
                time_limit=0.5
            )
            
            print("✓ 默认输入模式创建完成")
        except Exception as e:
            print(f"✗ 默认输入模式创建失败: {e}")
            
    def _create_default_sequences(self):
        """创建默认输入序列"""
        try:
            # 游戏秘籍示例
            self.create_input_sequence(
                name="unlimited_ammo",
                sequence=['o', 'n', 'e', 'u', 'p'],
                context=InputContext.GAMEPLAY,
                description="无限弹药秘籍"
            )
            
            print("✓ 默认输入序列创建完成")
        except Exception as e:
            print(f"✗ 默认输入序列创建失败: {e}")
            
    def _check_pattern_timeouts(self):
        """检查模式超时"""
        try:
            current_time = time.time()
            timed_out_patterns = []
            
            for pattern_id, pattern_data in self.pattern_start_time.items():
                if current_time - pattern_data > self.advanced_config['pattern_timeout']:
                    timed_out_patterns.append(pattern_id)
                    
            for pattern_id in timed_out_patterns:
                if pattern_id in self.pattern_start_time:
                    del self.pattern_start_time[pattern_id]
                    
        except Exception as e:
            print(f"✗ 模式超时检查失败: {e}")
            
    def _check_sequence_timeouts(self):
        """检查序列超时"""
        try:
            current_time = time.time()
            timed_out_sequences = []
            
            for sequence_id, sequence_data in self.sequence_start_time.items():
                if current_time - sequence_data > self.advanced_config['sequence_timeout']:
                    timed_out_sequences.append(sequence_id)
                    
            for sequence_id in timed_out_sequences:
                if sequence_id in self.sequence_start_time:
                    del self.sequence_start_time[sequence_id]
                    
        except Exception as e:
            print(f"✗ 序列超时检查失败: {e}")
            
    def _check_chord_timeouts(self):
        """检查和弦超时"""
        try:
            current_time = time.time()
            timed_out_chords = []
            
            for chord_id, chord_data in self.chord_inputs.items():
                if current_time - chord_data['start_time'] > self.advanced_config['chord_timeout']:
                    timed_out_chords.append(chord_id)
                    
            for chord_id in timed_out_chords:
                if chord_id in self.chord_inputs:
                    del self.chord_inputs[chord_id]
                    
        except Exception as e:
            print(f"✗ 和弦超时检查失败: {e}")
            
    def set_input_context(self, context: InputContext) -> bool:
        """
        设置输入上下文
        
        Args:
            context: 输入上下文
            
        Returns:
            是否设置成功
        """
        try:
            if context not in self.input_contexts:
                print(f"✗ 无效的输入上下文: {context.value}")
                return False
                
            old_context = self.current_context
            self.current_context = context
            
            # 更新上下文激活状态
            for ctx in self.input_contexts:
                self.input_contexts[ctx]['active'] = (ctx == context)
                
            # 更新上下文堆栈
            if context in self.context_stack:
                self.context_stack.remove(context)
            self.context_stack.append(context)
            
            # 触发上下文变更回调
            self._trigger_advanced_callback('context_changed', {
                'old_context': old_context.value,
                'new_context': context.value
            })
            
            self.advanced_stats['contexts_switched'] += 1
            print(f"✓ 输入上下文已设置: {context.value}")
            return True
            
        except Exception as e:
            print(f"✗ 输入上下文设置失败: {e}")
            return False
            
    def push_input_context(self, context: InputContext) -> bool:
        """
        推入输入上下文（保存当前上下文）
        
        Args:
            context: 输入上下文
            
        Returns:
            是否推入成功
        """
        try:
            if context not in self.input_contexts:
                print(f"✗ 无效的输入上下文: {context.value}")
                return False
                
            # 保存当前上下文
            self.context_stack.append(context)
            self.current_context = context
            
            # 更新上下文激活状态
            for ctx in self.input_contexts:
                self.input_contexts[ctx]['active'] = (ctx == context)
                
            # 触发上下文变更回调
            self._trigger_advanced_callback('context_changed', {
                'old_context': self.context_stack[-2].value if len(self.context_stack) > 1 else None,
                'new_context': context.value
            })
            
            self.advanced_stats['contexts_switched'] += 1
            print(f"✓ 输入上下文已推入: {context.value}")
            return True
            
        except Exception as e:
            print(f"✗ 输入上下文推入失败: {e}")
            return False
            
    def pop_input_context(self) -> bool:
        """
        弹出输入上下文（恢复上一个上下文）
        
        Returns:
            是否弹出成功
        """
        try:
            if len(self.context_stack) <= 1:
                print("✗ 无法弹出最后一个上下文")
                return False
                
            # 移除当前上下文
            self.context_stack.pop()
            
            # 恢复上一个上下文
            previous_context = self.context_stack[-1]
            self.current_context = previous_context
            
            # 更新上下文激活状态
            for ctx in self.input_contexts:
                self.input_contexts[ctx]['active'] = (ctx == previous_context)
                
            # 触发上下文变更回调
            self._trigger_advanced_callback('context_changed', {
                'old_context': self.context_stack[-2].value if len(self.context_stack) > 1 else None,
                'new_context': previous_context.value
            })
            
            self.advanced_stats['contexts_switched'] += 1
            print(f"✓ 输入上下文已弹出，恢复到: {previous_context.value}")
            return True
            
        except Exception as e:
            print(f"✗ 输入上下文弹出失败: {e}")
            return False
            
    def create_input_pattern(self, name: str, inputs: List[str], context: InputContext,
                           description: str = "", time_limit: float = None) -> int:
        """
        创建输入模式
        
        Args:
            name: 模式名称
            inputs: 输入序列
            context: 上下文
            description: 描述
            time_limit: 时间限制(秒)
            
        Returns:
            模式ID
        """
        try:
            pattern_id = self.pattern_counter
            self.pattern_counter += 1
            
            pattern = {
                'id': pattern_id,
                'name': name,
                'inputs': inputs,
                'context': context,
                'description': description,
                'time_limit': time_limit or self.advanced_config['pattern_timeout'],
                'created_time': time.time(),
                'match_count': 0
            }
            
            self.input_patterns[pattern_id] = pattern
            
            print(f"✓ 输入模式已创建: {name} (ID: {pattern_id})")
            return pattern_id
            
        except Exception as e:
            print(f"✗ 输入模式创建失败: {e}")
            return -1
            
    def remove_input_pattern(self, pattern_id: int) -> bool:
        """
        移除输入模式
        
        Args:
            pattern_id: 模式ID
            
        Returns:
            是否移除成功
        """
        try:
            if pattern_id in self.input_patterns:
                pattern_name = self.input_patterns[pattern_id]['name']
                del self.input_patterns[pattern_id]
                print(f"✓ 输入模式已移除: {pattern_name} (ID: {pattern_id})")
                return True
            else:
                print(f"✗ 输入模式不存在: ID {pattern_id}")
                return False
                
        except Exception as e:
            print(f"✗ 输入模式移除失败: {e}")
            return False
            
    def process_input_pattern(self, input_name: str) -> bool:
        """
        处理输入模式匹配
        
        Args:
            input_name: 输入名称
            
        Returns:
            是否匹配成功
        """
        try:
            current_time = time.time()
            matched_patterns = []
            
            for pattern_id, pattern in self.input_patterns.items():
                # 检查上下文是否匹配
                if pattern['context'] != self.current_context and pattern['context'] != InputContext.GLOBAL:
                    continue
                    
                # 初始化模式跟踪
                if pattern_id not in self.pattern_start_time:
                    self.pattern_start_time[pattern_id] = current_time
                    
                # 检查时间限制
                if current_time - self.pattern_start_time[pattern_id] > pattern['time_limit']:
                    continue
                    
                # 这里应该实现实际的模式匹配逻辑
                # 简化处理：只检查最后一个输入
                if pattern['inputs'] and pattern['inputs'][-1] == input_name:
                    matched_patterns.append(pattern_id)
                    
            # 处理匹配的模式
            for pattern_id in matched_patterns:
                pattern = self.input_patterns[pattern_id]
                pattern['match_count'] += 1
                self.advanced_stats['patterns_matched'] += 1
                
                # 触发模式匹配回调
                self._trigger_advanced_callback('pattern_matched', {
                    'pattern_id': pattern_id,
                    'pattern_name': pattern['name'],
                    'input': input_name
                })
                
                # 重置模式时间
                if pattern_id in self.pattern_start_time:
                    del self.pattern_start_time[pattern_id]
                    
                print(f"✓ 输入模式匹配: {pattern['name']}")
                
            return len(matched_patterns) > 0
            
        except Exception as e:
            print(f"✗ 输入模式处理失败: {e}")
            return False
            
    def create_input_sequence(self, name: str, sequence: List[str], context: InputContext,
                            description: str = "") -> int:
        """
        创建输入序列
        
        Args:
            name: 序列名称
            sequence: 输入序列
            context: 上下文
            description: 描述
            
        Returns:
            序列ID
        """
        try:
            sequence_id = self.sequence_counter
            self.sequence_counter += 1
            
            seq = {
                'id': sequence_id,
                'name': name,
                'sequence': sequence,
                'context': context,
                'description': description,
                'created_time': time.time(),
                'current_position': 0,
                'completion_count': 0
            }
            
            self.input_sequences[sequence_id] = seq
            
            print(f"✓ 输入序列已创建: {name} (ID: {sequence_id})")
            return sequence_id
            
        except Exception as e:
            print(f"✗ 输入序列创建失败: {e}")
            return -1
            
    def remove_input_sequence(self, sequence_id: int) -> bool:
        """
        移除输入序列
        
        Args:
            sequence_id: 序列ID
            
        Returns:
            是否移除成功
        """
        try:
            if sequence_id in self.input_sequences:
                sequence_name = self.input_sequences[sequence_id]['name']
                del self.input_sequences[sequence_id]
                print(f"✓ 输入序列已移除: {sequence_name} (ID: {sequence_id})")
                return True
            else:
                print(f"✗ 输入序列不存在: ID {sequence_id}")
                return False
                
        except Exception as e:
            print(f"✗ 输入序列移除失败: {e}")
            return False
            
    def process_input_sequence(self, input_name: str) -> bool:
        """
        处理输入序列
        
        Args:
            input_name: 输入名称
            
        Returns:
            是否完成序列
        """
        try:
            current_time = time.time()
            completed_sequences = []
            
            for sequence_id, sequence in self.input_sequences.items():
                # 检查上下文是否匹配
                if sequence['context'] != self.current_context and sequence['context'] != InputContext.GLOBAL:
                    continue
                    
                # 初始化序列时间
                if sequence_id not in self.sequence_start_time:
                    self.sequence_start_time[sequence_id] = current_time
                    sequence['current_position'] = 0
                    
                # 检查时间限制
                if current_time - self.sequence_start_time[sequence_id] > self.advanced_config['sequence_timeout']:
                    sequence['current_position'] = 0
                    self.sequence_start_time[sequence_id] = current_time
                    
                # 检查输入匹配
                if sequence['current_position'] < len(sequence['sequence']):
                    expected_input = sequence['sequence'][sequence['current_position']]
                    if input_name == expected_input:
                        sequence['current_position'] += 1
                        
                        # 检查序列是否完成
                        if sequence['current_position'] >= len(sequence['sequence']):
                            completed_sequences.append(sequence_id)
                            
            # 处理完成的序列
            for sequence_id in completed_sequences:
                sequence = self.input_sequences[sequence_id]
                sequence['completion_count'] += 1
                sequence['current_position'] = 0
                self.advanced_stats['sequences_completed'] += 1
                
                # 触发序列完成回调
                self._trigger_advanced_callback('sequence_completed', {
                    'sequence_id': sequence_id,
                    'sequence_name': sequence['name']
                })
                
                # 重置序列时间
                if sequence_id in self.sequence_start_time:
                    del self.sequence_start_time[sequence_id]
                    
                print(f"✓ 输入序列完成: {sequence['name']}")
                
            return len(completed_sequences) > 0
            
        except Exception as e:
            print(f"✗ 输入序列处理失败: {e}")
            return False
            
    def update_modifiers(self, modifier: str, pressed: bool):
        """
        更新修饰符状态
        
        Args:
            modifier: 修饰符名称
            pressed: 是否按下
        """
        try:
            if pressed:
                self.active_modifiers.add(modifier)
                self.advanced_stats['modifiers_activated'] += 1
                
                # 触发修饰符变更回调
                self._trigger_advanced_callback('modifier_changed', {
                    'modifier': modifier,
                    'state': 'pressed'
                })
            else:
                if modifier in self.active_modifiers:
                    self.active_modifiers.remove(modifier)
                    
                # 触发修饰符变更回调
                self._trigger_advanced_callback('modifier_changed', {
                    'modifier': modifier,
                    'state': 'released'
                })
                
        except Exception as e:
            print(f"✗ 修饰符更新失败: {e}")
            
    def is_modifier_active(self, modifier: str) -> bool:
        """
        检查修饰符是否激活
        
        Args:
            modifier: 修饰符名称
            
        Returns:
            是否激活
        """
        return modifier in self.active_modifiers
        
    def get_active_modifiers(self) -> Set[str]:
        """
        获取激活的修饰符列表
        
        Returns:
            激活的修饰符集合
        """
        return self.active_modifiers.copy()
        
    def process_timed_input(self, input_name: str, duration: float):
        """
        处理时间相关输入
        
        Args:
            input_name: 输入名称
            duration: 持续时间(秒)
        """
        try:
            # 检查是否为双击
            if duration < self.advanced_config['double_press_time']:
                last_time = self.last_input_time.get(input_name, 0)
                current_time = time.time()
                if current_time - last_time < self.advanced_config['double_press_time']:
                    # 双击事件
                    self._trigger_advanced_callback('timed_input', {
                        'input': input_name,
                        'type': 'double_click',
                        'duration': duration
                    })
                    self.advanced_stats['timed_inputs_processed'] += 1
                    
            # 检查是否为长按
            elif duration >= self.advanced_config['long_press_time']:
                # 长按事件
                self._trigger_advanced_callback('timed_input', {
                    'input': input_name,
                    'type': 'long_press',
                    'duration': duration
                })
                self.advanced_stats['timed_inputs_processed'] += 1
                
            # 更新最后输入时间
            self.last_input_time[input_name] = time.time()
            
        except Exception as e:
            print(f"✗ 时间相关输入处理失败: {e}")
            
    def _trigger_advanced_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发高级回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.advanced_callbacks:
                for callback in self.advanced_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 高级回调执行失败: {e}")
        except Exception as e:
            print(f"✗ 高级回调触发失败: {e}")
            
    def register_advanced_callback(self, callback_type: str, callback: Callable):
        """
        注册高级回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.advanced_callbacks:
                self.advanced_callbacks[callback_type].append(callback)
                print(f"✓ 高级回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 高级回调注册失败: {e}")
            
    def unregister_advanced_callback(self, callback_type: str, callback: Callable):
        """
        注销高级回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.advanced_callbacks:
                if callback in self.advanced_callbacks[callback_type]:
                    self.advanced_callbacks[callback_type].remove(callback)
                    print(f"✓ 高级回调已注销: {callback_type}")
        except Exception as e:
            print(f"✗ 高级回调注销失败: {e}")
            
    def get_current_context(self) -> InputContext:
        """
        获取当前输入上下文
        
        Returns:
            当前输入上下文
        """
        return self.current_context
        
    def get_context_stack(self) -> List[InputContext]:
        """
        获取上下文堆栈
        
        Returns:
            上下文堆栈列表
        """
        return self.context_stack.copy()
        
    def get_input_patterns(self) -> Dict[int, Dict[str, Any]]:
        """
        获取所有输入模式
        
        Returns:
            输入模式字典
        """
        return self.input_patterns.copy()
        
    def get_input_sequences(self) -> Dict[int, Dict[str, Any]]:
        """
        获取所有输入序列
        
        Returns:
            输入序列字典
        """
        return self.input_sequences.copy()
        
    def set_advanced_config(self, config: Dict[str, Any]) -> bool:
        """
        设置高级配置
        
        Args:
            config: 高级配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.advanced_config.update(config)
            print(f"✓ 高级配置已更新: {self.advanced_config}")
            return True
        except Exception as e:
            print(f"✗ 高级配置设置失败: {e}")
            return False
            
    def get_advanced_config(self) -> Dict[str, Any]:
        """
        获取高级配置
        
        Returns:
            高级配置字典
        """
        return self.advanced_config.copy()
        
    def get_advanced_stats(self) -> Dict[str, int]:
        """
        获取高级统计信息
        
        Returns:
            高级统计字典
        """
        return self.advanced_stats.copy()
        
    def reset_advanced_stats(self):
        """重置高级统计信息"""
        try:
            self.advanced_stats = {
                'contexts_switched': 0,
                'patterns_matched': 0,
                'sequences_completed': 0,
                'modifiers_activated': 0,
                'timed_inputs_processed': 0
            }
            print("✓ 高级统计信息已重置")
        except Exception as e:
            print(f"✗ 高级统计信息重置失败: {e}")
            
    def get_context_info(self, context: InputContext) -> Optional[Dict[str, Any]]:
        """
        获取上下文信息
        
        Args:
            context: 输入上下文
            
        Returns:
            上下文信息字典或None
        """
        return self.input_contexts.get(context)