"""
语音管理器模块
负责管理语音识别和合成的核心功能
"""

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

class VoiceManager:
    """
    语音管理器
    负责管理语音识别和合成的核心功能
    """
    
    def __init__(self, plugin):
        """
        初始化语音管理器
        
        Args:
            plugin: 语音控制插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 语音识别状态
        self.recognition_state = {
            'is_listening': False,
            'is_processing': False,
            'last_recognition_time': 0.0,
            'current_text': '',
            'confidence': 0.0
        }
        
        # 语音合成状态
        self.synthesis_state = {
            'is_speaking': False,
            'is_processing': False,
            'last_synthesis_time': 0.0,
            'current_text': '',
            'progress': 0.0
        }
        
        # 配置参数
        self.voice_config = {
            'enable_voice_control': True,
            'enable_voice_feedback': True,
            'recognition_language': 'zh-CN',
            'synthesis_language': 'zh-CN',
            'synthesis_voice': 'default',
            'recognition_sensitivity': 0.5,
            'synthesis_speed': 1.0,
            'synthesis_volume': 1.0,
            'enable_wake_word': True,
            'wake_word': '小艾',
            'enable_continuous_listening': True,
            'silence_timeout': 3.0
        }
        
        # 命令历史
        self.command_history = []
        self.max_history_size = 100
        
        # 关键词列表
        self.keywords = []
        
        # 统计信息
        self.stats = {
            'commands_processed': 0,
            'speech_recognized': 0,
            'speech_synthesized': 0,
            'recognition_errors': 0,
            'synthesis_errors': 0,
            'wake_word_detected': 0
        }
        
        # 线程管理
        self.update_thread = None
        self.running = False
        
        # 回调函数
        self.voice_callbacks = {
            'speech_recognized': [],
            'speech_synthesis_started': [],
            'speech_synthesis_completed': [],
            'command_processed': [],
            'wake_word_detected': []
        }
        
        # 时间戳记录
        self.last_update_time = 0.0
        self.last_wake_word_time = 0.0
        
        print("✓ 语音管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化语音管理器
        
        Returns:
            是否初始化成功
        """
        try:
            # 初始化关键词列表
            self._initialize_keywords()
            
            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.update_thread = threading.Thread(target=self._update_loop, daemon=True)
            self.update_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.update_thread and self.update_thread.is_alive():
                self.update_thread.join(timeout=1.0)
                
            print("✓ 语音管理器已禁用")
            
        except Exception as e:
            print(f"✗ 语音管理器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理语音管理器资源"""
        try:
            self.disable()
            self.voice_callbacks.clear()
            self.command_history.clear()
            self.keywords.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
                
            current_time = time.time()
            self.last_update_time = current_time
            
        except Exception as e:
            print(f"✗ 语音管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _initialize_keywords(self):
        """初始化关键词列表"""
        try:
            # 添加默认关键词
            default_keywords = [
                '前进', '后退', '左转', '右转', '停止',
                '开始', '结束', '暂停', '继续', '取消',
                '打开', '关闭', '增加', '减少', '设置',
                '帮助', '关于', '退出', '返回', '确认'
            ]
            
            self.keywords.extend(default_keywords)
            print("✓ 关键词列表初始化完成")
        except Exception as e:
            print(f"✗ 关键词列表初始化失败: {e}")
            
    def _update_loop(self):
        """更新循环线程"""
        try:
            update_interval = 1.0 / 30.0  # 30Hz
            
            while self.running:
                if self.enabled:
                    self._update_voice_state()
                    
                time.sleep(update_interval)
                
        except Exception as e:
            print(f"✗ 语音管理器更新循环失败: {e}")
            
    def _update_voice_state(self):
        """更新语音状态"""
        try:
            current_time = time.time()
            
            # 检查静默超时
            if self.recognition_state['is_listening']:
                if current_time - self.recognition_state['last_recognition_time'] > self.voice_config['silence_timeout']:
                    self.recognition_state['is_listening'] = False
                    
        except Exception as e:
            print(f"✗ 语音状态更新失败: {e}")
            
    def start_listening(self) -> bool:
        """
        开始语音识别监听
        
        Returns:
            是否开始成功
        """
        try:
            if not self.enabled:
                print("✗ 语音管理器未启用")
                return False
                
            self.recognition_state['is_listening'] = True
            self.recognition_state['last_recognition_time'] = time.time()
            
            print("✓ 语音识别监听已开始")
            return True
            
        except Exception as e:
            print(f"✗ 语音识别监听开始失败: {e}")
            self.stats['recognition_errors'] += 1
            return False
            
    def stop_listening(self) -> bool:
        """
        停止语音识别监听
        
        Returns:
            是否停止成功
        """
        try:
            self.recognition_state['is_listening'] = False
            print("✓ 语音识别监听已停止")
            return True
            
        except Exception as e:
            print(f"✗ 语音识别监听停止失败: {e}")
            return False
            
    def process_speech(self, text: str, confidence: float = 1.0) -> bool:
        """
        处理识别到的语音文本
        
        Args:
            text: 识别到的文本
            confidence: 置信度(0.0-1.0)
            
        Returns:
            是否处理成功
        """
        try:
            if not self.enabled:
                print("✗ 语音管理器未启用")
                return False
                
            # 更新识别状态
            self.recognition_state['current_text'] = text
            self.recognition_state['confidence'] = confidence
            self.recognition_state['last_recognition_time'] = time.time()
            
            # 检查唤醒词
            if self.voice_config['enable_wake_word']:
                if self._check_wake_word(text):
                    self._trigger_voice_callback('wake_word_detected', {
                        'text': text,
                        'confidence': confidence
                    })
                    self.stats['wake_word_detected'] += 1
                    self.last_wake_word_time = time.time()
                    
                    # 如果启用了连续监听，开始处理命令
                    if self.voice_config['enable_continuous_listening']:
                        # 移除唤醒词并处理剩余文本
                        command_text = self._remove_wake_word(text)
                        return self._process_command(command_text, confidence)
                    return True
                    
            # 处理命令
            if not self.voice_config['enable_wake_word'] or \
               (time.time() - self.last_wake_word_time) < 5.0:  # 5秒内有效
                return self._process_command(text, confidence)
                
            self.stats['speech_recognized'] += 1
            return True
            
        except Exception as e:
            print(f"✗ 语音文本处理失败: {e}")
            self.stats['recognition_errors'] += 1
            return False
            
    def _check_wake_word(self, text: str) -> bool:
        """
        检查是否包含唤醒词
        
        Args:
            text: 识别到的文本
            
        Returns:
            是否包含唤醒词
        """
        try:
            wake_word = self.voice_config['wake_word']
            return wake_word in text
        except Exception as e:
            print(f"✗ 唤醒词检查失败: {e}")
            return False
            
    def _remove_wake_word(self, text: str) -> str:
        """
        移除唤醒词
        
        Args:
            text: 包含唤醒词的文本
            
        Returns:
            移除唤醒词后的文本
        """
        try:
            wake_word = self.voice_config['wake_word']
            return text.replace(wake_word, '').strip()
        except Exception as e:
            print(f"✗ 唤醒词移除失败: {e}")
            return text
            
    def _process_command(self, text: str, confidence: float) -> bool:
        """
        处理语音命令
        
        Args:
            text: 命令文本
            confidence: 置信度
            
        Returns:
            是否处理成功
        """
        try:
            # 添加到命令历史
            command_entry = {
                'text': text,
                'confidence': confidence,
                'timestamp': time.time()
            }
            
            self.command_history.append(command_entry)
            
            # 保持历史记录大小
            if len(self.command_history) > self.max_history_size:
                self.command_history.pop(0)
                
            # 触发命令处理回调
            self._trigger_voice_callback('command_processed', {
                'text': text,
                'confidence': confidence,
                'command_entry': command_entry
            })
            
            # 交给命令处理器处理
            if self.plugin.command_processor:
                self.plugin.command_processor.process_command(text, confidence)
                
            self.stats['commands_processed'] += 1
            return True
            
        except Exception as e:
            print(f"✗ 命令处理失败: {e}")
            return False
            
    def speak_text(self, text: str, blocking: bool = False) -> bool:
        """
        语音合成播放文本
        
        Args:
            text: 要合成的文本
            blocking: 是否阻塞等待播放完成
            
        Returns:
            是否播放成功
        """
        try:
            if not self.enabled:
                print("✗ 语音管理器未启用")
                return False
                
            if not self.voice_config['enable_voice_feedback']:
                print("✗ 语音反馈未启用")
                return False
                
            # 更新合成状态
            self.synthesis_state['is_speaking'] = True
            self.synthesis_state['is_processing'] = True
            self.synthesis_state['current_text'] = text
            self.synthesis_state['last_synthesis_time'] = time.time()
            
            # 触发合成开始回调
            self._trigger_voice_callback('speech_synthesis_started', {
                'text': text
            })
            
            # 交给语音合成器处理
            if self.plugin.speech_synthesizer:
                result = self.plugin.speech_synthesizer.synthesize_speech(
                    text, blocking, 
                    self.voice_config['synthesis_speed'],
                    self.voice_config['synthesis_volume']
                )
                
                if result:
                    self.stats['speech_synthesized'] += 1
                    return True
                else:
                    self.stats['synthesis_errors'] += 1
                    return False
            else:
                print("✗ 语音合成器未初始化")
                self.stats['synthesis_errors'] += 1
                return False
                
        except Exception as e:
            print(f"✗ 文本语音合成失败: {e}")
            self.stats['synthesis_errors'] += 1
            return False
        finally:
            # 更新合成状态
            self.synthesis_state['is_speaking'] = False
            self.synthesis_state['is_processing'] = False
            
            # 触发合成完成回调
            self._trigger_voice_callback('speech_synthesis_completed', {
                'text': text
            })
            
    def add_keyword(self, keyword: str) -> bool:
        """
        添加关键词
        
        Args:
            keyword: 关键词
            
        Returns:
            是否添加成功
        """
        try:
            if keyword not in self.keywords:
                self.keywords.append(keyword)
                print(f"✓ 关键词已添加: {keyword}")
                return True
            else:
                print(f"⚠ 关键词已存在: {keyword}")
                return True
        except Exception as e:
            print(f"✗ 关键词添加失败: {e}")
            return False
            
    def remove_keyword(self, keyword: str) -> bool:
        """
        移除关键词
        
        Args:
            keyword: 关键词
            
        Returns:
            是否移除成功
        """
        try:
            if keyword in self.keywords:
                self.keywords.remove(keyword)
                print(f"✓ 关键词已移除: {keyword}")
                return True
            else:
                print(f"⚠ 关键词不存在: {keyword}")
                return False
        except Exception as e:
            print(f"✗ 关键词移除失败: {e}")
            return False
            
    def get_keywords(self) -> List[str]:
        """
        获取关键词列表
        
        Returns:
            关键词列表
        """
        return self.keywords.copy()
        
    def set_voice_config(self, config: Dict[str, Any]) -> bool:
        """
        设置语音配置
        
        Args:
            config: 配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.voice_config.update(config)
            print(f"✓ 语音配置已更新: {self.voice_config}")
            return True
        except Exception as e:
            print(f"✗ 语音配置设置失败: {e}")
            return False
            
    def get_voice_config(self) -> Dict[str, Any]:
        """
        获取语音配置
        
        Returns:
            配置字典
        """
        return self.voice_config.copy()
        
    def get_recognition_state(self) -> Dict[str, Any]:
        """
        获取识别状态
        
        Returns:
            识别状态字典
        """
        return self.recognition_state.copy()
        
    def get_synthesis_state(self) -> Dict[str, Any]:
        """
        获取合成状态
        
        Returns:
            合成状态字典
        """
        return self.synthesis_state.copy()
        
    def get_command_history(self) -> List[Dict[str, Any]]:
        """
        获取命令历史
        
        Returns:
            命令历史列表
        """
        return self.command_history.copy()
        
    def clear_command_history(self):
        """清空命令历史"""
        try:
            self.command_history.clear()
            print("✓ 命令历史已清空")
        except Exception as e:
            print(f"✗ 命令历史清空失败: {e}")
            
    def _trigger_voice_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发语音回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.voice_callbacks:
                for callback in self.voice_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 语音回调执行失败: {e}")
        except Exception as e:
            print(f"✗ 语音回调触发失败: {e}")
            
    def register_voice_callback(self, callback_type: str, callback: callable):
        """
        注册语音回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.voice_callbacks:
                self.voice_callbacks[callback_type].append(callback)
                print(f"✓ 语音回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 语音回调注册失败: {e}")
            
    def unregister_voice_callback(self, callback_type: str, callback: callable):
        """
        注销语音回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.voice_callbacks:
                if callback in self.voice_callbacks[callback_type]:
                    self.voice_callbacks[callback_type].remove(callback)
                    print(f"✓ 语音回调已注销: {callback_type}")
        except Exception as e:
            print(f"✗ 语音回调注销失败: {e}")
            
    def get_stats(self) -> Dict[str, int]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        try:
            self.stats = {
                'commands_processed': 0,
                'speech_recognized': 0,
                'speech_synthesized': 0,
                'recognition_errors': 0,
                'synthesis_errors': 0,
                'wake_word_detected': 0
            }
            print("✓ 语音管理器统计信息已重置")
        except Exception as e:
            print(f"✗ 语音管理器统计信息重置失败: {e}")