"""
音乐管理器
负责音乐主题的加载、播放和控制
"""

import uuid
import math
import time
import numpy as np
from typing import Dict, List, Any, Optional
from panda3d.core import AudioSound
import scipy.signal as signal

class MusicManager:
    """
    音乐管理器
    负责音乐主题的加载、播放和控制
    """
    
    def __init__(self, plugin):
        """
        初始化音乐管理器
        
        Args:
            plugin: 动态音乐系统插件实例
        """
        self.plugin = plugin
        self.themes: Dict[str, Dict[str, Any]] = {}
        self.layers: Dict[str, Dict[str, Any]] = {}
        self.active_themes: Dict[str, Dict[str, Any]] = {}
        self.layer_volumes: Dict[str, float] = {}
        self.sound_cache: Dict[str, AudioSound] = {}
        
        self.stats = {
            'themes_loaded': 0,
            'themes_active': 0,
            'layers_active': 0,
            'sounds_played': 0,
            'processing_time': 0.0,
            'memory_usage': 0
        }
        
        self.master_volume = 1.0
        self.crossfade_duration = 2.0
        self.buffer_size = plugin.buffer_size if plugin else 4096
        self.sample_rate = 44100
        
        # 音乐处理参数
        self.equalizer_settings = {
            'low_freq': 100.0,
            'mid_freq': 1000.0,
            'high_freq': 8000.0,
            'low_gain': 0.0,
            'mid_gain': 0.0,
            'high_gain': 0.0
        }
        
        # 音乐播放状态
        self.playback_state = {
            'current_position': 0.0,
            'total_duration': 0.0,
            'is_paused': False,
            'loop_count': 0
        }
        
        # 音乐缓冲区
        self.audio_buffers = {}
        self.fade_buffers = {}
        
        # 初始化音乐管理器
        self._initialize_music_manager()
        
    def _initialize_music_manager(self):
        """初始化音乐管理器"""
        print("✓ 音乐管理器初始化完成")
        
    def load_theme(self, theme_name: str, theme_data: Dict[str, Any]) -> bool:
        """
        加载音乐主题
        
        Args:
            theme_name: 主题名称
            theme_data: 主题数据
            
        Returns:
            是否加载成功
        """
        try:
            # 存储主题数据
            self.themes[theme_name] = theme_data.copy()
            
            # 加载主题中的所有层
            layers = theme_data.get('layers', [])
            for layer_name in layers:
                if layer_name not in self.layers:
                    self.load_layer(layer_name)
                    
            self.stats['themes_loaded'] += 1
            print(f"✓ 音乐主题加载成功: {theme_name}")
            return True
            
        except Exception as e:
            print(f"✗ 加载音乐主题失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def load_layer(self, layer_name: str, layer_data: Dict[str, Any] = None) -> bool:
        """
        加载音乐层
        
        Args:
            layer_name: 层名称
            layer_data: 层数据（可选）
            
        Returns:
            是否加载成功
        """
        try:
            # 如果没有提供层数据，创建默认数据
            if layer_data is None:
                layer_data = {
                    'volume': 1.0,
                    'loop': True,
                    'priority': 1,
                    'filepath': f"music/layers/{layer_name}.wav",
                    'format': 'wav',
                    'channels': 2,
                    'sample_rate': 44100,
                    'bit_depth': 16
                }
                
            # 存储层数据
            self.layers[layer_name] = layer_data.copy()
            
            # 设置默认音量
            self.layer_volumes[layer_name] = layer_data.get('volume', 1.0)
            
            # 创建音频缓冲区
            buffer_size = self.buffer_size
            self.audio_buffers[layer_name] = np.zeros(buffer_size)
            
            print(f"✓ 音乐层加载成功: {layer_name}")
            return True
            
        except Exception as e:
            print(f"✗ 加载音乐层失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def play_theme(self, theme_name: str, force: bool = False) -> bool:
        """
        播放音乐主题
        
        Args:
            theme_name: 主题名称
            force: 是否强制播放（跳过过渡）
            
        Returns:
            是否播放成功
        """
        try:
            if theme_name not in self.themes:
                print(f"✗ 音乐主题不存在: {theme_name}")
                return False
                
            theme_data = self.themes[theme_name]
            layers = theme_data.get('layers', [])
            
            # 创建主题实例
            theme_instance = {
                'name': theme_name,
                'layers': {},
                'start_time': time.time(),
                'volume': 1.0,
                'state': 'playing',
                'bpm': theme_data.get('bpm', 120),
                'key': theme_data.get('key', 'C'),
                'mood': theme_data.get('mood', 'neutral'),
                'loop': theme_data.get('loop', True),
                'fade_in_progress': 0.0,
                'fade_in_duration': 0.0
            }
            
            # 加载并播放所有层
            for layer_name in layers:
                if self.play_layer(layer_name):
                    theme_instance['layers'][layer_name] = {
                        'name': layer_name,
                        'volume': self.layer_volumes.get(layer_name, 1.0),
                        'state': 'playing',
                        'position': 0.0,
                        'duration': 0.0
                    }
                    
            # 存储活动主题
            self.active_themes[theme_name] = theme_instance
            self.stats['themes_active'] = len(self.active_themes)
            self.stats['layers_active'] = sum(len(theme['layers']) for theme in self.active_themes.values())
            
            print(f"✓ 音乐主题开始播放: {theme_name}")
            return True
            
        except Exception as e:
            print(f"✗ 播放音乐主题失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def play_layer(self, layer_name: str) -> bool:
        """
        播放音乐层
        
        Args:
            layer_name: 层名称
            
        Returns:
            是否播放成功
        """
        try:
            if layer_name not in self.layers:
                # 如果层不存在，创建一个虚拟层
                self.load_layer(layer_name)
                
            # 模拟播放音频文件
            # 在实际实现中，这里会使用Panda3D的音频系统
            layer_data = self.layers[layer_name]
            
            # 初始化音频缓冲区
            buffer_size = self.buffer_size
            if layer_name not in self.audio_buffers:
                self.audio_buffers[layer_name] = np.zeros(buffer_size)
                
            # 生成测试音频信号
            self._generate_test_audio(layer_name, layer_data)
            
            print(f"✓ 音乐层开始播放: {layer_name}")
            self.stats['sounds_played'] += 1
            return True
            
        except Exception as e:
            print(f"✗ 播放音乐层失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def _generate_test_audio(self, layer_name: str, layer_data: Dict[str, Any]):
        """
        生成测试音频信号
        
        Args:
            layer_name: 层名称
            layer_data: 层数据
        """
        try:
            # 获取层的音频参数
            sample_rate = layer_data.get('sample_rate', self.sample_rate)
            duration = 10.0  # 10秒测试音频
            samples = int(sample_rate * duration)
            
            # 生成不同频率的正弦波组合来模拟音乐层
            t = np.linspace(0, duration, samples, False)
            
            # 基频基于层名称和参数
            base_freq = 220.0  # A3音符
            if 'bass' in layer_name.lower():
                base_freq = 110.0  # A2音符（低音）
            elif 'high' in layer_name.lower():
                base_freq = 440.0  # A4音符（高音）
            elif 'melody' in layer_name.lower():
                base_freq = 330.0  # E4音符（中音）
                
            # 生成音频信号
            audio_signal = np.sin(2 * np.pi * base_freq * t)
            
            # 添加谐波丰富音色
            harmonics = [0.5, 0.3, 0.2, 0.1]
            for i, harmonic in enumerate(harmonics, 2):
                audio_signal += harmonic * np.sin(2 * np.pi * base_freq * i * t)
                
            # 应用包络（模拟音符起音和释放）
            envelope = np.ones_like(t)
            attack_time = int(0.1 * sample_rate)  # 0.1秒起音
            release_time = int(0.2 * sample_rate)  # 0.2秒释放
            
            if len(envelope) > attack_time:
                envelope[:attack_time] = np.linspace(0, 1, attack_time)
            if len(envelope) > release_time:
                envelope[-release_time:] = np.linspace(1, 0, release_time)
                
            audio_signal *= envelope
            
            # 应用层音量
            volume = self.layer_volumes.get(layer_name, 1.0)
            audio_signal *= volume
            
            # 存储到缓冲区（循环存储）
            buffer = self.audio_buffers[layer_name]
            for i in range(min(len(buffer), len(audio_signal))):
                buffer[i] = audio_signal[i % len(audio_signal)]
                
        except Exception as e:
            print(f"✗ 生成测试音频失败: {e}")
            
    def stop_theme(self, theme_name: str) -> bool:
        """
        停止音乐主题
        
        Args:
            theme_name: 主题名称
            
        Returns:
            是否停止成功
        """
        try:
            if theme_name not in self.active_themes:
                print(f"⚠ 音乐主题未在播放: {theme_name}")
                return True
                
            # 停止主题中的所有层
            theme_instance = self.active_themes[theme_name]
            for layer_name in theme_instance['layers']:
                self.stop_layer(layer_name)
                
            # 移除活动主题
            del self.active_themes[theme_name]
            self.stats['themes_active'] = len(self.active_themes)
            self.stats['layers_active'] = sum(len(theme['layers']) for theme in self.active_themes.values())
            
            print(f"✓ 音乐主题已停止: {theme_name}")
            return True
            
        except Exception as e:
            print(f"✗ 停止音乐主题失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def stop_layer(self, layer_name: str) -> bool:
        """
        停止音乐层
        
        Args:
            layer_name: 层名称
            
        Returns:
            是否停止成功
        """
        try:
            # 模拟停止音频文件
            # 在实际实现中，这里会使用Panda3D的音频系统
            if layer_name in self.audio_buffers:
                # 清空音频缓冲区
                self.audio_buffers[layer_name].fill(0.0)
                
            print(f"✓ 音乐层已停止: {layer_name}")
            return True
            
        except Exception as e:
            print(f"✗ 停止音乐层失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def stop_all(self):
        """停止所有音乐"""
        try:
            # 停止所有活动主题
            active_themes = list(self.active_themes.keys())
            for theme_name in active_themes:
                self.stop_theme(theme_name)
                
            print("✓ 所有音乐已停止")
            
        except Exception as e:
            print(f"✗ 停止所有音乐失败: {e}")
            import traceback
            traceback.print_exc()
            
    def set_theme_volume(self, theme_name: str, volume: float):
        """
        设置主题音量
        
        Args:
            theme_name: 主题名称
            volume: 音量值 (0.0-1.0)
        """
        volume = max(0.0, min(1.0, volume))
        
        if theme_name in self.active_themes:
            theme_instance = self.active_themes[theme_name]
            theme_instance['volume'] = volume
            
            # 更新主题中所有层的音量
            for layer_name in theme_instance['layers']:
                self.set_layer_volume(layer_name, volume)
                
            print(f"✓ 主题 {theme_name} 音量设置为: {volume:.2f}")
            
    def set_layer_volume(self, layer_name: str, volume: float):
        """
        设置层音量
        
        Args:
            layer_name: 层名称
            volume: 音量值 (0.0-1.0)
        """
        volume = max(0.0, min(1.0, volume))
        self.layer_volumes[layer_name] = volume
        
        # 在实际实现中，这里会更新音频实例的音量
        # 对于测试音频，我们调整缓冲区的音量
        if layer_name in self.audio_buffers:
            # 这里简化处理，实际应用中会更复杂
            pass
            
        print(f"✓ 层 {layer_name} 音量设置为: {volume:.2f}")
        
    def set_master_volume(self, volume: float):
        """
        设置主音量
        
        Args:
            volume: 主音量 (0.0-1.0)
        """
        self.master_volume = max(0.0, min(1.0, volume))
        print(f"✓ 主音量设置为: {self.master_volume:.2f}")
        
    def fade_out_theme(self, theme_name: str, duration: float = 2.0):
        """
        淡出音乐主题
        
        Args:
            theme_name: 主题名称
            duration: 淡出持续时间（秒）
        """
        try:
            if theme_name in self.active_themes:
                theme_instance = self.active_themes[theme_name]
                theme_instance['state'] = 'fading_out'
                theme_instance['fade_start_time'] = time.time()
                theme_instance['fade_duration'] = duration
                theme_instance['fade_start_volume'] = theme_instance['volume']
                
                print(f"✓ 主题 {theme_name} 开始淡出，持续时间: {duration:.2f}秒")
                
        except Exception as e:
            print(f"✗ 淡出主题失败: {e}")
            import traceback
            traceback.print_exc()
            
    def fade_in_theme(self, theme_name: str, duration: float = 2.0):
        """
        淡入音乐主题
        
        Args:
            theme_name: 主题名称
            duration: 淡入持续时间（秒）
        """
        try:
            if theme_name in self.themes and theme_name not in self.active_themes:
                # 先播放主题
                self.play_theme(theme_name)
                
                # 设置淡入状态
                if theme_name in self.active_themes:
                    theme_instance = self.active_themes[theme_name]
                    theme_instance['state'] = 'fading_in'
                    theme_instance['fade_start_time'] = time.time()
                    theme_instance['fade_duration'] = duration
                    theme_instance['fade_start_volume'] = 0.0
                    theme_instance['target_volume'] = theme_instance['volume']
                    theme_instance['volume'] = 0.0
                    self.set_theme_volume(theme_name, 0.0)
                    
                print(f"✓ 主题 {theme_name} 开始淡入，持续时间: {duration:.2f}秒")
                
        except Exception as e:
            print(f"✗ 淡入主题失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_active_themes(self) -> List[str]:
        """
        获取活动主题列表
        
        Returns:
            活动主题名称列表
        """
        return list(self.active_themes.keys())
        
    def get_theme_status(self, theme_name: str) -> Dict[str, Any]:
        """
        获取主题状态
        
        Args:
            theme_name: 主题名称
            
        Returns:
            主题状态字典
        """
        if theme_name in self.active_themes:
            theme_instance = self.active_themes[theme_name]
            return {
                'name': theme_name,
                'state': theme_instance['state'],
                'volume': theme_instance['volume'],
                'layers': list(theme_instance['layers'].keys()),
                'start_time': theme_instance['start_time'],
                'bpm': theme_instance['bpm'],
                'key': theme_instance['key'],
                'mood': theme_instance['mood']
            }
        else:
            return {
                'name': theme_name,
                'state': 'stopped',
                'volume': 0.0,
                'layers': [],
                'start_time': 0.0,
                'bpm': 0,
                'key': '',
                'mood': ''
            }
            
    def get_layer_status(self, layer_name: str) -> Dict[str, Any]:
        """
        获取层状态
        
        Args:
            layer_name: 层名称
            
        Returns:
            层状态字典
        """
        return {
            'name': layer_name,
            'volume': self.layer_volumes.get(layer_name, 0.0),
            'loaded': layer_name in self.layers,
            'active': any(
                layer_name in theme['layers'] 
                for theme in self.active_themes.values()
            )
        }
        
    def update(self, dt: float):
        """
        更新音乐管理器状态
        
        Args:
            dt: 时间增量
        """
        update_start_time = time.time()
        
        # 更新淡入淡出效果
        current_time = time.time()
        themes_to_remove = []
        
        for theme_name, theme_instance in self.active_themes.items():
            if theme_instance['state'] in ['fading_in', 'fading_out']:
                fade_start_time = theme_instance.get('fade_start_time', current_time)
                fade_duration = theme_instance.get('fade_duration', 1.0)
                fade_start_volume = theme_instance.get('fade_start_volume', 0.0)
                elapsed_time = current_time - fade_start_time
                
                if elapsed_time >= fade_duration:
                    # 淡入淡出完成
                    if theme_instance['state'] == 'fading_out':
                        themes_to_remove.append(theme_name)
                        theme_instance['state'] = 'stopped'
                        self.set_theme_volume(theme_name, 0.0)
                    else:  # fading_in
                        theme_instance['state'] = 'playing'
                        target_volume = theme_instance.get('target_volume', 1.0)
                        self.set_theme_volume(theme_name, target_volume)
                else:
                    # 计算当前音量
                    progress = elapsed_time / fade_duration
                    if theme_instance['state'] == 'fading_out':
                        current_volume = fade_start_volume * (1.0 - progress)
                    else:  # fading_in
                        target_volume = theme_instance.get('target_volume', 1.0)
                        current_volume = fade_start_volume + (target_volume - fade_start_volume) * progress
                        
                    self.set_theme_volume(theme_name, current_volume)
                    
        # 移除已停止的主题
        for theme_name in themes_to_remove:
            if theme_name in self.active_themes:
                del self.active_themes[theme_name]
                
        self.stats['themes_active'] = len(self.active_themes)
        self.stats['layers_active'] = sum(len(theme['layers']) for theme in self.active_themes.values())
        
        # 更新音频播放位置
        self._update_playback_positions(dt)
        
        # 更新性能统计
        self.stats['processing_time'] += (time.time() - update_start_time)
        
    def _update_playback_positions(self, dt: float):
        """
        更新音频播放位置
        
        Args:
            dt: 时间增量
        """
        # 更新播放状态
        self.playback_state['current_position'] += dt
        if self.playback_state['current_position'] > self.playback_state['total_duration']:
            self.playback_state['current_position'] = 0.0
            self.playback_state['loop_count'] += 1
            
    def cleanup(self):
        """清理所有资源"""
        self.stop_all()
        self.themes.clear()
        self.layers.clear()
        self.active_themes.clear()
        self.layer_volumes.clear()
        self.sound_cache.clear()
        self.audio_buffers.clear()
        self.fade_buffers.clear()
        
        self.stats = {
            'themes_loaded': 0,
            'themes_active': 0,
            'layers_active': 0,
            'sounds_played': 0,
            'processing_time': 0.0,
            'memory_usage': 0
        }
        
        print("✓ 音乐管理器资源已清理")
        
    def get_stats(self) -> Dict[str, int]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def preload_theme(self, theme_name: str) -> bool:
        """
        预加载音乐主题
        
        Args:
            theme_name: 主题名称
            
        Returns:
            是否预加载成功
        """
        try:
            if theme_name not in self.themes:
                print(f"✗ 音乐主题不存在: {theme_name}")
                return False
                
            theme_data = self.themes[theme_name]
            layers = theme_data.get('layers', [])
            
            # 预加载所有层
            for layer_name in layers:
                if layer_name not in self.sound_cache:
                    # 在实际实现中，这里会加载音频文件到缓存
                    self.sound_cache[layer_name] = None  # 占位符
                    # 同时预加载层数据
                    if layer_name not in self.layers:
                        self.load_layer(layer_name)
                    
            print(f"✓ 音乐主题预加载成功: {theme_name}")
            return True
            
        except Exception as e:
            print(f"✗ 预加载音乐主题失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def set_crossfade_duration(self, duration: float):
        """
        设置交叉淡入淡出持续时间
        
        Args:
            duration: 持续时间（秒）
        """
        self.crossfade_duration = max(0.1, duration)
        print(f"✓ 交叉淡入淡出持续时间设置为: {self.crossfade_duration:.2f}秒")
        
    def get_master_volume(self) -> float:
        """
        获取主音量
        
        Returns:
            主音量 (0.0-1.0)
        """
        return self.master_volume
        
    def is_theme_playing(self, theme_name: str) -> bool:
        """
        检查主题是否正在播放
        
        Args:
            theme_name: 主题名称
            
        Returns:
            是否正在播放
        """
        return theme_name in self.active_themes
        
    def set_equalizer(self, low_gain: float = 0.0, mid_gain: float = 0.0, high_gain: float = 0.0):
        """
        设置均衡器参数
        
        Args:
            low_gain: 低频增益 (-24.0 to 24.0 dB)
            mid_gain: 中频增益 (-24.0 to 24.0 dB)
            high_gain: 高频增益 (-24.0 to 24.0 dB)
        """
        self.equalizer_settings['low_gain'] = max(-24.0, min(24.0, low_gain))
        self.equalizer_settings['mid_gain'] = max(-24.0, min(24.0, mid_gain))
        self.equalizer_settings['high_gain'] = max(-24.0, min(24.0, high_gain))
        print(f"✓ 均衡器设置: 低频={low_gain:.1f}dB, 中频={mid_gain:.1f}dB, 高频={high_gain:.1f}dB")
        
    def get_audio_data(self, layer_name: str, num_samples: int = None) -> np.ndarray:
        """
        获取音频数据
        
        Args:
            layer_name: 层名称
            num_samples: 样本数量
            
        Returns:
            音频数据数组
        """
        if layer_name in self.audio_buffers:
            buffer = self.audio_buffers[layer_name]
            if num_samples is None:
                return buffer.copy()
            else:
                return buffer[:min(num_samples, len(buffer))].copy()
        else:
            return np.zeros(num_samples if num_samples else self.buffer_size)
            
    def set_layer_position(self, layer_name: str, position: float):
        """
        设置层播放位置
        
        Args:
            layer_name: 层名称
            position: 播放位置（秒）
        """
        if layer_name in self.active_themes:
            for theme in self.active_themes.values():
                if layer_name in theme['layers']:
                    theme['layers'][layer_name]['position'] = max(0.0, position)
                    print(f"✓ 层 {layer_name} 播放位置设置为: {position:.2f}秒")
                    return
        print(f"⚠ 层 {layer_name} 未在播放，无法设置位置")
        
    def get_layer_position(self, layer_name: str) -> float:
        """
        获取层播放位置
        
        Args:
            layer_name: 层名称
            
        Returns:
            播放位置（秒）
        """
        for theme in self.active_themes.values():
            if layer_name in theme['layers']:
                return theme['layers'][layer_name].get('position', 0.0)
        return 0.0
        
    def set_layer_loop(self, layer_name: str, loop: bool):
        """
        设置层循环播放
        
        Args:
            layer_name: 层名称
            loop: 是否循环播放
        """
        if layer_name in self.layers:
            self.layers[layer_name]['loop'] = loop
            print(f"✓ 层 {layer_name} 循环播放已{'启用' if loop else '禁用'}")
        else:
            print(f"✗ 层 {layer_name} 不存在")
            
    def is_layer_looping(self, layer_name: str) -> bool:
        """
        检查层是否循环播放
        
        Args:
            layer_name: 层名称
            
        Returns:
            是否循环播放
        """
        return self.layers.get(layer_name, {}).get('loop', False)
        
    def set_theme_bpm(self, theme_name: str, bpm: float):
        """
        设置主题BPM
        
        Args:
            theme_name: 主题名称
            bpm: 每分钟节拍数
        """
        if theme_name in self.themes:
            self.themes[theme_name]['bpm'] = max(30, min(300, bpm))
            if theme_name in self.active_themes:
                self.active_themes[theme_name]['bpm'] = bpm
            print(f"✓ 主题 {theme_name} BPM设置为: {bpm}")
        else:
            print(f"✗ 主题 {theme_name} 不存在")
            
    def get_theme_bpm(self, theme_name: str) -> float:
        """
        获取主题BPM
        
        Args:
            theme_name: 主题名称
            
        Returns:
            BPM值
        """
        theme_bpm = self.themes.get(theme_name, {}).get('bpm', 120.0)
        if theme_name in self.active_themes:
            return self.active_themes[theme_name].get('bpm', theme_bpm)
        return theme_bpm
        
    def set_theme_key(self, theme_name: str, key: str):
        """
        设置主题调号
        
        Args:
            theme_name: 主题名称
            key: 调号
        """
        valid_keys = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
        if key.upper() not in valid_keys:
            print(f"✗ 无效的调号: {key}")
            return
            
        if theme_name in self.themes:
            self.themes[theme_name]['key'] = key.upper()
            if theme_name in self.active_themes:
                self.active_themes[theme_name]['key'] = key.upper()
            print(f"✓ 主题 {theme_name} 调号设置为: {key.upper()}")
        else:
            print(f"✗ 主题 {theme_name} 不存在")
            
    def get_theme_key(self, theme_name: str) -> str:
        """
        获取主题调号
        
        Args:
            theme_name: 主题名称
            
        Returns:
            调号
        """
        theme_key = self.themes.get(theme_name, {}).get('key', 'C')
        if theme_name in self.active_themes:
            return self.active_themes[theme_name].get('key', theme_key)
        return theme_key
        
    def set_theme_mood(self, theme_name: str, mood: str):
        """
        设置主题情绪
        
        Args:
            theme_name: 主题名称
            mood: 情绪标签
        """
        valid_moods = ['calm', 'tense', 'epic', 'melancholic', 'joyful', 'mysterious', 'heroic', 'romantic']
        if mood.lower() not in valid_moods:
            print(f"⚠ 未知的情绪标签: {mood}，将使用自定义标签")
            
        if theme_name in self.themes:
            self.themes[theme_name]['mood'] = mood.lower()
            if theme_name in self.active_themes:
                self.active_themes[theme_name]['mood'] = mood.lower()
            print(f"✓ 主题 {theme_name} 情绪设置为: {mood.lower()}")
        else:
            print(f"✗ 主题 {theme_name} 不存在")
            
    def get_theme_mood(self, theme_name: str) -> str:
        """
        获取主题情绪
        
        Args:
            theme_name: 主题名称
            
        Returns:
            情绪标签
        """
        theme_mood = self.themes.get(theme_name, {}).get('mood', 'neutral')
        if theme_name in self.active_themes:
            return self.active_themes[theme_name].get('mood', theme_mood)
        return theme_mood
        
    def get_playback_state(self) -> Dict[str, Any]:
        """
        获取播放状态
        
        Returns:
            播放状态字典
        """
        return self.playback_state.copy()
        
    def pause_theme(self, theme_name: str) -> bool:
        """
        暂停主题播放
        
        Args:
            theme_name: 主题名称
            
        Returns:
            是否暂停成功
        """
        if theme_name in self.active_themes:
            theme_instance = self.active_themes[theme_name]
            if theme_instance['state'] == 'playing':
                theme_instance['state'] = 'paused'
                theme_instance['pause_time'] = time.time()
                print(f"✓ 主题 {theme_name} 已暂停")
                return True
            else:
                print(f"⚠ 主题 {theme_name} 不在播放状态")
                return False
        else:
            print(f"✗ 主题 {theme_name} 未在播放")
            return False
            
    def resume_theme(self, theme_name: str) -> bool:
        """
        恢复主题播放
        
        Args:
            theme_name: 主题名称
            
        Returns:
            是否恢复成功
        """
        if theme_name in self.active_themes:
            theme_instance = self.active_themes[theme_name]
            if theme_instance['state'] == 'paused':
                theme_instance['state'] = 'playing'
                # 计算暂停时间并调整开始时间
                if 'pause_time' in theme_instance:
                    pause_duration = time.time() - theme_instance['pause_time']
                    if 'fade_start_time' in theme_instance:
                        theme_instance['fade_start_time'] += pause_duration
                print(f"✓ 主题 {theme_name} 已恢复播放")
                return True
            else:
                print(f"⚠ 主题 {theme_name} 不在暂停状态")
                return False
        else:
            print(f"✗ 主题 {theme_name} 未在播放")
            return False
            
    def set_sample_rate(self, sample_rate: int):
        """
        设置采样率
        
        Args:
            sample_rate: 采样率 (Hz)
        """
        old_sample_rate = self.sample_rate
        self.sample_rate = sample_rate
        print(f"✓ 音乐管理器采样率已从 {old_sample_rate} 更新为: {sample_rate} Hz")
        
        # 重新生成所有音频缓冲区
        for layer_name in self.audio_buffers.keys():
            if layer_name in self.layers:
                self._generate_test_audio(layer_name, self.layers[layer_name])