"""
语音控制插件
为EG引擎提供完整的语音识别和语音合成功能
"""

from .core.voice_manager import VoiceManager
from .recognition.speech_recognizer import SpeechRecognizer
from .synthesis.speech_synthesizer import SpeechSynthesizer
from .commands.command_processor import CommandProcessor
from .audio.audio_manager import AudioManager
from .events.event_handler import VoiceEventHandler
from .nlp.nlp_processor import NLPProcessor
from .config.config_manager import VoiceConfigManager
from .editor.voice_editor import VoiceEditor
from .utils.voice_utils import VoiceUtils

class VoiceControlPlugin:
    """
    语音控制插件主类
    整合所有语音控制功能模块
    """
    
    def __init__(self, engine):
        """
        初始化语音控制插件
        
        Args:
            engine: EG引擎实例
        """
        self.engine = engine
        self.name = "VoiceControl"
        self.version = "1.0.0"
        self.author = "EG Plugin System"
        
        # 功能模块
        self.voice_manager = None
        self.speech_recognizer = None
        self.speech_synthesizer = None
        self.command_processor = None
        self.audio_manager = None
        self.event_handler = None
        self.nlp_processor = None
        self.config_manager = None
        self.voice_editor = None
        self.voice_utils = None
        
        # 插件状态
        self.enabled = False
        self.initialized = False
        
        # 性能统计
        self.stats = {
            'commands_processed': 0,
            'speech_recognized': 0,
            'speech_synthesized': 0,
            'audio_devices': 0,
            'recognition_errors': 0,
            'synthesis_errors': 0
        }
        
        print(f"✓ 语音控制插件 v{self.version} 已创建")
        
    def initialize(self) -> bool:
        """
        初始化插件
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化语音控制插件...")
            
            # 初始化核心组件
            self.voice_manager = VoiceManager(self)
            self.speech_recognizer = SpeechRecognizer(self)
            self.speech_synthesizer = SpeechSynthesizer(self)
            self.command_processor = CommandProcessor(self)
            self.audio_manager = AudioManager(self)
            self.event_handler = VoiceEventHandler(self)
            self.nlp_processor = NLPProcessor(self)
            self.config_manager = VoiceConfigManager(self)
            self.voice_editor = VoiceEditor(self)
            self.voice_utils = VoiceUtils(self)
            
            # 初始化各个模块
            modules = [
                self.voice_manager,
                self.speech_recognizer,
                self.speech_synthesizer,
                self.command_processor,
                self.audio_manager,
                self.event_handler,
                self.nlp_processor,
                self.config_manager,
                self.voice_editor,
                self.voice_utils
            ]
            
            for module in modules:
                if module and not module.initialize():
                    print(f"✗ 模块初始化失败: {module.__class__.__name__}")
                    return False
                    
            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
                
            print("正在启用语音控制插件...")
            
            # 启用各个模块
            modules = [
                self.voice_manager,
                self.speech_recognizer,
                self.speech_synthesizer,
                self.command_processor,
                self.audio_manager,
                self.event_handler,
                self.nlp_processor,
                self.config_manager,
                self.voice_editor,
                self.voice_utils
            ]
            
            for module in modules:
                if module and not module.enable():
                    print(f"✗ 模块启用失败: {module.__class__.__name__}")
                    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:
            if not self.enabled:
                return
                
            print("正在禁用语音控制插件...")
            
            # 禁用各个模块
            modules = [
                self.voice_manager,
                self.speech_recognizer,
                self.speech_synthesizer,
                self.command_processor,
                self.audio_manager,
                self.event_handler,
                self.nlp_processor,
                self.config_manager,
                self.voice_editor,
                self.voice_utils
            ]
            
            for module in modules:
                if module:
                    module.disable()
                    
            self.enabled = False
            print("✓ 语音控制插件已禁用")
            
        except Exception as e:
            print(f"✗ 语音控制插件禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理插件资源"""
        try:
            print("正在清理语音控制插件资源...")
            
            # 清理各个模块
            modules = [
                self.voice_manager,
                self.speech_recognizer,
                self.speech_synthesizer,
                self.command_processor,
                self.audio_manager,
                self.event_handler,
                self.nlp_processor,
                self.config_manager,
                self.voice_editor,
                self.voice_utils
            ]
            
            for module in modules:
                if module:
                    module.finalize()
                    
            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
                
            # 更新各个模块
            modules = [
                self.voice_manager,
                self.speech_recognizer,
                self.speech_synthesizer,
                self.command_processor,
                self.audio_manager,
                self.event_handler,
                self.nlp_processor,
                self.config_manager,
                self.voice_editor,
                self.voice_utils
            ]
            
            for module in modules:
                if module:
                    module.update(dt)
                    
        except Exception as e:
            print(f"✗ 语音控制插件更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_stats(self) -> dict:
        """
        获取插件统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'commands_processed': 0,
            'speech_recognized': 0,
            'speech_synthesized': 0,
            'audio_devices': 0,
            'recognition_errors': 0,
            'synthesis_errors': 0
        }
        print("✓ 语音控制统计信息已重置")