"""
季节管理器
负责管理季节变化和季节相关参数
"""

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

class SeasonManager:
    """
    季节管理器
    负责管理季节变化、季节参数和季节过渡效果
    """
    
    def __init__(self, plugin):
        """
        初始化季节管理器
        
        Args:
            plugin: 天气和季节系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 季节配置
        self.seasons = {
            'spring': {
                'name': '春季',
                'description': '万物复苏的季节',
                'temperature': 15.0,  # 平均温度(摄氏度)
                'humidity': 60.0,     # 平均湿度(%)
                'day_length': 12.5,   # 日照时长(小时)
                'transition_duration': 7.0,  # 季节过渡持续时间(天)
                'color_tint': (1.0, 1.0, 0.8),  # 颜色色调(RGB)
                'vegetation_growth': 0.7,       # 植被生长状态(0-1)
                'precipitation_frequency': 0.3  # 降水频率(0-1)
            },
            'summer': {
                'name': '夏季',
                'description': '炎热的季节',
                'temperature': 28.0,
                'humidity': 70.0,
                'day_length': 14.5,
                'transition_duration': 7.0,
                'color_tint': (1.0, 0.9, 0.7),
                'vegetation_growth': 1.0,
                'precipitation_frequency': 0.4
            },
            'autumn': {
                'name': '秋季',
                'description': '收获的季节',
                'temperature': 12.0,
                'humidity': 55.0,
                'day_length': 11.5,
                'transition_duration': 7.0,
                'color_tint': (1.0, 0.8, 0.6),
                'vegetation_growth': 0.5,
                'precipitation_frequency': 0.25
            },
            'winter': {
                'name': '冬季',
                'description': '寒冷的季节',
                'temperature': -2.0,
                'humidity': 45.0,
                'day_length': 9.0,
                'transition_duration': 7.0,
                'color_tint': (0.8, 0.8, 1.0),
                'vegetation_growth': 0.1,
                'precipitation_frequency': 0.2
            }
        }
        
        # 当前季节状态
        self.current_season = 'spring'
        self.target_season = 'spring'
        self.season_transition_progress = 0.0  # 季节过渡进度(0-1)
        self.season_transition_active = False
        
        # 季节时间配置
        self.season_duration = 90  # 每个季节持续天数
        self.current_day_in_season = 0  # 当前季节中的天数
        self.total_days = 0  # 总天数
        
        # 季节循环配置
        self.season_cycle_enabled = True
        self.season_order = ['spring', 'summer', 'autumn', 'winter']
        
        # 统计信息
        self.stats = {
            'seasons_changed': 0,
            'transitions_completed': 0,
            'total_season_time': 0.0
        }
        
        # 编辑器相关
        self.is_being_edited = False
        self.edit_timestamp = 0
        self.edit_history = []
        self.max_history_size = 100
        
        print("✓ 季节管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化季节管理器
        
        Returns:
            是否初始化成功
        """
        try:
            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.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._update_season_time(dt)
            
            # 更新季节过渡
            if self.season_transition_active:
                self._update_season_transition(dt)
                
        except Exception as e:
            print(f"✗ 季节管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_season_time(self, dt: float):
        """
        更新季节时间
        
        Args:
            dt: 时间增量
        """
        try:
            # 假设1秒代表1小时游戏时间
            hours_passed = dt / 1.0
            
            # 更新当前季节中的天数
            self.current_day_in_season += hours_passed / 24.0
            self.total_days += hours_passed / 24.0
            
            # 检查是否需要切换季节
            if self.current_day_in_season >= self.season_duration and self.season_cycle_enabled:
                self._transition_to_next_season()
                
        except Exception as e:
            print(f"✗ 季节时间更新失败: {e}")
            
    def _transition_to_next_season(self):
        """过渡到下一个季节"""
        try:
            # 找到当前季节在顺序中的位置
            current_index = self.season_order.index(self.current_season)
            
            # 计算下一个季节
            next_index = (current_index + 1) % len(self.season_order)
            self.target_season = self.season_order[next_index]
            
            # 启动季节过渡
            self.start_season_transition()
            
        except Exception as e:
            print(f"✗ 季节切换失败: {e}")
            
    def start_season_transition(self):
        """开始季节过渡"""
        try:
            if self.current_season == self.target_season:
                return
                
            self.season_transition_active = True
            self.season_transition_progress = 0.0
            
            print(f"✓ 开始季节过渡: {self.current_season} -> {self.target_season}")
            
        except Exception as e:
            print(f"✗ 季节过渡启动失败: {e}")
            
    def _update_season_transition(self, dt: float):
        """
        更新季节过渡
        
        Args:
            dt: 时间增量
        """
        try:
            if not self.season_transition_active:
                return
                
            # 假设1秒代表1小时游戏时间
            hours_passed = dt / 1.0
            
            # 获取过渡持续时间（天）
            transition_duration = self.seasons[self.target_season]['transition_duration']
            
            # 计算进度增量（每小时进度）
            progress_per_hour = 1.0 / (transition_duration * 24.0)
            progress_delta = progress_per_hour * hours_passed
            
            # 更新过渡进度
            self.season_transition_progress += progress_delta
            
            # 检查过渡是否完成
            if self.season_transition_progress >= 1.0:
                self._complete_season_transition()
                
        except Exception as e:
            print(f"✗ 季节过渡更新失败: {e}")
            
    def _complete_season_transition(self):
        """完成季节过渡"""
        try:
            # 更新当前季节
            self.current_season = self.target_season
            
            # 重置季节内天数
            self.current_day_in_season = 0
            
            # 重置过渡状态
            self.season_transition_active = False
            self.season_transition_progress = 0.0
            
            # 更新统计信息
            self.stats['seasons_changed'] += 1
            self.stats['transitions_completed'] += 1
            
            print(f"✓ 季节过渡完成: 现在是{self.seasons[self.current_season]['name']}")
            
            # 触发季节变化事件
            self._trigger_season_change_event()
            
        except Exception as e:
            print(f"✗ 季节过渡完成失败: {e}")
            
    def _trigger_season_change_event(self):
        """触发季节变化事件"""
        try:
            # 在实际实现中，这里会触发一个事件通知其他系统季节已变化
            pass
        except Exception as e:
            print(f"✗ 季节变化事件触发失败: {e}")
            
    def set_current_season(self, season: str):
        """
        设置当前季节
        
        Args:
            season: 季节名称 ('spring', 'summer', 'autumn', 'winter')
        """
        try:
            if season not in self.seasons:
                print(f"✗ 无效的季节: {season}")
                return
                
            self.current_season = season
            self.current_day_in_season = 0
            
            print(f"✓ 当前季节设置为: {self.seasons[season]['name']}")
            
        except Exception as e:
            print(f"✗ 当前季节设置失败: {e}")
            
    def set_target_season(self, season: str):
        """
        设置目标季节
        
        Args:
            season: 季节名称 ('spring', 'summer', 'autumn', 'winter')
        """
        try:
            if season not in self.seasons:
                print(f"✗ 无效的季节: {season}")
                return
                
            self.target_season = season
            self.start_season_transition()
            
        except Exception as e:
            print(f"✗ 目标季节设置失败: {e}")
            
    def set_season_duration(self, days: int):
        """
        设置季节持续时间
        
        Args:
            days: 持续天数
        """
        if days > 0:
            self.season_duration = days
            print(f"✓ 季节持续时间设置为: {days} 天")
        else:
            print("✗ 无效的季节持续时间")
            
    def enable_season_cycle(self, enabled: bool):
        """
        启用/禁用季节循环
        
        Args:
            enabled: 是否启用季节循环
        """
        self.season_cycle_enabled = enabled
        print(f"✓ 季节循环{'已启用' if enabled else '已禁用'}")
        
    def get_current_season(self) -> str:
        """
        获取当前季节
        
        Returns:
            当前季节名称
        """
        return self.current_season
        
    def get_season_info(self, season: str = None) -> Optional[Dict[str, Any]]:
        """
        获取季节信息
        
        Args:
            season: 季节名称（如果为None，则返回当前季节信息）
            
        Returns:
            季节信息字典或None
        """
        try:
            if season is None:
                season = self.current_season
                
            if season not in self.seasons:
                return None
                
            return self.seasons[season].copy()
            
        except Exception as e:
            print(f"✗ 季节信息获取失败: {e}")
            return None
            
    def get_interpolated_season_params(self) -> Dict[str, Any]:
        """
        获取插值后的季节参数（考虑季节过渡）
        
        Returns:
            插值后的季节参数字典
        """
        try:
            if not self.season_transition_active or self.season_transition_progress <= 0.0:
                # 没有过渡，返回当前季节参数
                return self.seasons[self.current_season].copy()
                
            if self.season_transition_progress >= 1.0:
                # 过渡完成，返回目标季节参数
                return self.seasons[self.target_season].copy()
                
            # 进行插值计算
            current_params = self.seasons[self.current_season]
            target_params = self.seasons[self.target_season]
            
            interpolated_params = {}
            
            # 对数值参数进行线性插值
            numeric_params = ['temperature', 'humidity', 'day_length', 'vegetation_growth', 'precipitation_frequency']
            for param in numeric_params:
                current_value = current_params[param]
                target_value = target_params[param]
                interpolated_value = current_value + (target_value - current_value) * self.season_transition_progress
                interpolated_params[param] = interpolated_value
                
            # 对颜色进行插值
            current_color = current_params['color_tint']
            target_color = target_params['color_tint']
            interpolated_color = tuple(
                current_color[i] + (target_color[i] - current_color[i]) * self.season_transition_progress
                for i in range(3)
            )
            interpolated_params['color_tint'] = interpolated_color
            
            # 复制非数值参数
            interpolated_params['name'] = f"{current_params['name']} → {target_params['name']}"
            interpolated_params['description'] = f"过渡季节 ({self.season_transition_progress*100:.1f}%)"
            interpolated_params['transition_duration'] = target_params['transition_duration']
            
            return interpolated_params
            
        except Exception as e:
            print(f"✗ 插值季节参数获取失败: {e}")
            return self.seasons[self.current_season].copy()
            
    def get_season_progress(self) -> float:
        """
        获取当前季节进度
        
        Returns:
            季节进度 (0-1)
        """
        if self.season_duration > 0:
            return min(1.0, self.current_day_in_season / self.season_duration)
        return 0.0
        
    def get_transition_progress(self) -> float:
        """
        获取季节过渡进度
        
        Returns:
            过渡进度 (0-1)
        """
        return self.season_transition_progress
        
    def is_transition_active(self) -> bool:
        """
        检查是否正在进行季节过渡
        
        Returns:
            是否正在进行季节过渡
        """
        return self.season_transition_active
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'seasons_changed': 0,
            'transitions_completed': 0,
            'total_season_time': 0.0
        }
        print("✓ 季节管理器统计信息已重置")
        
    def get_season_list(self) -> List[str]:
        """
        获取所有季节列表
        
        Returns:
            季节名称列表
        """
        return list(self.seasons.keys())
        
    def get_season_name(self, season: str) -> str:
        """
        获取季节显示名称
        
        Args:
            season: 季节名称
            
        Returns:
            季节显示名称
        """
        if season in self.seasons:
            return self.seasons[season]['name']
        return season
        
    def _save_edit_history(self):
        """保存编辑历史"""
        try:
            # 创建当前状态快照
            snapshot = {
                'timestamp': time.time(),
                'current_season': self.current_season,
                'target_season': self.target_season,
                'season_duration': self.season_duration,
                'season_cycle_enabled': self.season_cycle_enabled,
                'season_transition_active': self.season_transition_active,
                'season_transition_progress': self.season_transition_progress
            }
            
            # 添加到历史记录
            self.edit_history.append(snapshot)
            
            # 限制历史记录大小
            if len(self.edit_history) > self.max_history_size:
                self.edit_history.pop(0)
                
        except Exception as e:
            print(f"✗ 编辑历史保存失败: {e}")
            
    def undo_edit(self) -> bool:
        """
        撤销编辑
        
        Returns:
            是否撤销成功
        """
        try:
            if not self.edit_history:
                print("✗ 没有可撤销的编辑")
                return False
                
            # 恢复到上一个状态
            last_state = self.edit_history.pop()
            
            # 恢复参数
            self.current_season = last_state['current_season']
            self.target_season = last_state['target_season']
            self.season_duration = last_state['season_duration']
            self.season_cycle_enabled = last_state['season_cycle_enabled']
            self.season_transition_active = last_state['season_transition_active']
            self.season_transition_progress = last_state['season_transition_progress']
            
            print("✓ 编辑已撤销")
            return True
            
        except Exception as e:
            print(f"✗ 编辑撤销失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def get_edit_history_size(self) -> int:
        """
        获取编辑历史大小
        
        Returns:
            编辑历史记录数量
        """
        return len(self.edit_history)
        
    def clear_edit_history(self):
        """清空编辑历史"""
        try:
            self.edit_history.clear()
            print("✓ 编辑历史已清空")
        except Exception as e:
            print(f"✗ 编辑历史清空失败: {e}")
            
    def get_current_state_info(self) -> Dict[str, Any]:
        """
        获取当前状态信息
        
        Returns:
            当前状态信息字典
        """
        try:
            return {
                'current_season': self.current_season,
                'target_season': self.target_season,
                'season_duration': self.season_duration,
                'season_cycle_enabled': self.season_cycle_enabled,
                'season_transition_active': self.season_transition_active,
                'season_transition_progress': self.season_transition_progress,
                'current_day_in_season': self.current_day_in_season,
                'is_being_edited': self.is_being_edited,
                'edit_timestamp': self.edit_timestamp,
                'edit_history_size': len(self.edit_history)
            }
        except Exception as e:
            print(f"✗ 当前状态信息获取失败: {e}")
            return {}