"""
季节效应系统
负责模拟季节变化对植被和生态系统的影响
"""

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

class SeasonalEffects:
    """
    季节效应系统
    负责模拟季节变化对植被生长、动物行为和生态系统动态的影响
    """
    
    def __init__(self, plugin):
        """
        初始化季节效应系统
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 季节定义
        self.seasons = {
            'spring': {
                'name': '春季',
                'description': '万物复苏的季节',
                'temperature_modifier': 10.0,   # 温度修正
                'humidity_modifier': 15.0,      # 湿度修正
                'light_duration': 13.0,         # 光照时长(小时)
                'growth_factor': 1.5,           # 生长因子
                'reproduction_factor': 2.0,     # 繁殖因子
                'color_tint': (1.0, 1.0, 0.8),  # 颜色色调
                'duration': 90                  # 持续天数
            },
            'summer': {
                'name': '夏季',
                'description': '炎热的季节',
                'temperature_modifier': 20.0,
                'humidity_modifier': 10.0,
                'light_duration': 15.0,
                'growth_factor': 1.2,
                'reproduction_factor': 1.5,
                'color_tint': (1.0, 0.9, 0.7),
                'duration': 90
            },
            'autumn': {
                'name': '秋季',
                'description': '收获的季节',
                'temperature_modifier': 5.0,
                'humidity_modifier': 5.0,
                'light_duration': 11.0,
                'growth_factor': 0.5,
                'reproduction_factor': 0.8,
                'color_tint': (1.0, 0.7, 0.5),
                'duration': 90
            },
            'winter': {
                'name': '冬季',
                'description': '寒冷的季节',
                'temperature_modifier': -10.0,
                'humidity_modifier': 0.0,
                'light_duration': 9.0,
                'growth_factor': 0.1,
                'reproduction_factor': 0.2,
                'color_tint': (0.8, 0.8, 1.0),
                'duration': 90
            }
        }
        
        # 当前季节状态
        self.current_season = 'spring'
        self.season_progress = 0.0  # 季节进度 (0.0-1.0)
        self.season_day = 0         # 当前季节中的天数
        self.total_days = 0         # 总天数
        
        # 季节过渡参数
        self.transition_params = {
            'duration': 7.0,         # 过渡持续时间(天)
            'transition_active': False,
            'transition_progress': 0.0,
            'target_season': 'spring'
        }
        
        # 季节性事件
        self.seasonal_events = {
            'spring': ['花开', '鸟类迁徙回归', '动物繁殖季开始'],
            'summer': ['高温', '干旱', '虫害高发'],
            'autumn': ['叶色变化', '果实成熟', '动物准备过冬'],
            'winter': ['降雪', '动物冬眠', '植物休眠']
        }
        
        # 季节性动物行为
        self.animal_behaviors = {
            'migration': {
                'spring': 0.8,    # 春季迁徙概率
                'summer': 0.1,
                'autumn': 0.9,
                'winter': 0.2
            },
            'hibernation': {
                'spring': 0.1,
                'summer': 0.05,
                'autumn': 0.3,
                'winter': 0.9
            },
            'breeding': {
                'spring': 0.9,
                'summer': 0.7,
                'autumn': 0.3,
                'winter': 0.1
            }
        }
        
        # 季节性植被变化
        self.vegetation_changes = {
            'leaf_color': {
                'spring': (0.3, 0.7, 0.3),   # 绿色
                'summer': (0.2, 0.8, 0.2),
                'autumn': (0.8, 0.5, 0.2),   # 橙色
                'winter': (0.7, 0.7, 0.7)    # 灰色
            },
            'flowering': {
                'spring': 0.8,
                'summer': 0.4,
                'autumn': 0.1,
                'winter': 0.0
            },
            'fruiting': {
                'spring': 0.0,
                'summer': 0.2,
                'autumn': 0.9,
                'winter': 0.0
            }
        }
        
        # 时间配置
        self.time_config = {
            'day_length': 24.0,      # 一天长度(小时)
            'simulation_speed': 1.0,  # 模拟速度
            'current_time': 0.0      # 当前时间
        }
        
        # 统计信息
        self.season_stats = {
            'seasons_passed': 0,
            'transitions_completed': 0,
            'events_triggered': 0,
            'total_simulation_time': 0.0
        }
        
        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.time_config['current_time'] += dt * self.time_config['simulation_speed']
            
            # 更新季节进度
            self._update_season_progress(dt)
            
            # 更新季节过渡
            if self.transition_params['transition_active']:
                self._update_season_transition(dt)
                
            # 更新统计信息
            self.season_stats['total_simulation_time'] += dt
            
        except Exception as e:
            print(f"✗ 季节效应系统更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_season_progress(self, dt: float):
        """
        更新季节进度
        
        Args:
            dt: 时间增量
        """
        try:
            # 将时间增量转换为小时
            hours_passed = dt / 3600 * self.time_config['simulation_speed']
            
            # 更新当前季节中的天数
            self.season_day += hours_passed / 24.0
            self.total_days += hours_passed / 24.0
            
            # 更新季节进度
            current_season_info = self.seasons[self.current_season]
            self.season_progress = min(1.0, self.season_day / current_season_info['duration'])
            
            # 检查是否需要切换季节
            if self.season_day >= current_season_info['duration']:
                self._transition_to_next_season()
                
        except Exception as e:
            print(f"✗ 季节进度更新失败: {e}")
            
    def _transition_to_next_season(self):
        """过渡到下一个季节"""
        try:
            # 季节顺序
            season_order = ['spring', 'summer', 'autumn', 'winter']
            
            # 找到当前季节在顺序中的位置
            current_index = season_order.index(self.current_season)
            
            # 计算下一个季节
            next_index = (current_index + 1) % len(season_order)
            next_season = season_order[next_index]
            
            # 开始季节过渡
            self.start_season_transition(next_season)
            
        except Exception as e:
            print(f"✗ 季节切换失败: {e}")
            
    def start_season_transition(self, target_season: str):
        """
        开始季节过渡
        
        Args:
            target_season: 目标季节
        """
        try:
            if target_season not in self.seasons:
                print(f"✗ 无效的目标季节: {target_season}")
                return
                
            if target_season == self.current_season:
                return  # 季节未变化
                
            self.transition_params['target_season'] = target_season
            self.transition_params['transition_active'] = True
            self.transition_params['transition_progress'] = 0.0
            
            print(f"✓ 开始季节过渡: {self.seasons[self.current_season]['name']} -> {self.seasons[target_season]['name']}")
            
        except Exception as e:
            print(f"✗ 季节过渡启动失败: {e}")
            
    def _update_season_transition(self, dt: float):
        """
        更新季节过渡
        
        Args:
            dt: 时间增量
        """
        try:
            if not self.transition_params['transition_active']:
                return
                
            # 计算过渡进度增量
            transition_duration = self.transition_params['duration']
            if transition_duration > 0:
                progress_delta = dt / (transition_duration * 86400) * self.time_config['simulation_speed']
                self.transition_params['transition_progress'] += progress_delta
                
                # 检查过渡是否完成
                if self.transition_params['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.transition_params['target_season']
            
            # 重置季节内天数
            self.season_day = 0
            self.season_progress = 0.0
            
            # 重置过渡状态
            self.transition_params['transition_active'] = False
            self.transition_params['transition_progress'] = 0.0
            
            # 更新统计信息
            self.season_stats['seasons_passed'] += 1
            self.season_stats['transitions_completed'] += 1
            
            print(f"✓ 季节过渡完成: 现在是{self.seasons[self.current_season]['name']}")
            
            # 触发季节事件
            self._trigger_seasonal_events()
            
            # 通知其他系统季节已变化
            self._notify_systems_of_season_change()
            
        except Exception as e:
            print(f"✗ 季节过渡完成失败: {e}")
            
    def _trigger_seasonal_events(self):
        """触发季节性事件"""
        try:
            events = self.seasonal_events.get(self.current_season, [])
            if events:
                # 随机触发一个事件
                event = random.choice(events)
                print(f"✓ 季节性事件触发: {event}")
                self.season_stats['events_triggered'] += 1
                
        except Exception as e:
            print(f"✗ 季节性事件触发失败: {e}")
            
    def _notify_systems_of_season_change(self):
        """通知其他系统季节已变化"""
        try:
            # 通知植被管理器
            if self.plugin.vegetation_manager:
                # 更新环境因子
                current_season_info = self.seasons[self.current_season]
                environment_factors = {
                    'temperature': 20.0 + current_season_info['temperature_modifier'],
                    'humidity': 50.0 + current_season_info['humidity_modifier']
                }
                self.plugin.vegetation_manager.update_environment_factors(environment_factors)
                
        except Exception as e:
            print(f"✗ 系统通知失败: {e}")
            
    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 in self.seasons:
                return self.seasons[season].copy()
            return None
            
        except Exception as e:
            print(f"✗ 季节信息获取失败: {e}")
            return None
            
    def get_season_progress(self) -> float:
        """
        获取季节进度
        
        Returns:
            季节进度 (0.0-1.0)
        """
        return self.season_progress
        
    def get_season_day(self) -> int:
        """
        获取当前季节中的天数
        
        Returns:
            当前季节中的天数
        """
        return int(self.season_day)
        
    def set_current_season(self, season: str):
        """
        设置当前季节
        
        Args:
            season: 季节名称
        """
        try:
            if season in self.seasons:
                self.current_season = season
                self.season_day = 0
                self.season_progress = 0.0
                print(f"✓ 当前季节设置为: {self.seasons[season]['name']}")
            else:
                print(f"✗ 无效的季节: {season}")
                
        except Exception as e:
            print(f"✗ 当前季节设置失败: {e}")
            
    def set_season_duration(self, season: str, duration: int):
        """
        设置季节持续时间
        
        Args:
            season: 季节名称
            duration: 持续时间(天)
        """
        try:
            if season in self.seasons:
                self.seasons[season]['duration'] = max(1, duration)
                print(f"✓ {self.seasons[season]['name']} 持续时间设置为: {duration} 天")
            else:
                print(f"✗ 无效的季节: {season}")
                
        except Exception as e:
            print(f"✗ 季节持续时间设置失败: {e}")
            
    def get_interpolated_season_params(self) -> Dict[str, Any]:
        """
        获取插值后的季节参数（考虑季节过渡）
        
        Returns:
            插值后的季节参数字典
        """
        try:
            if not self.transition_params['transition_active'] or self.transition_params['transition_progress'] <= 0.0:
                # 没有过渡，返回当前季节参数
                return self.seasons[self.current_season].copy()
                
            if self.transition_params['transition_progress'] >= 1.0:
                # 过渡完成，返回目标季节参数
                return self.seasons[self.transition_params['target_season']].copy()
                
            # 进行插值计算
            current_params = self.seasons[self.current_season]
            target_params = self.seasons[self.transition_params['target_season']]
            
            interpolated_params = {}
            
            # 对数值参数进行线性插值
            numeric_params = [
                'temperature_modifier', 'humidity_modifier', 'light_duration',
                'growth_factor', 'reproduction_factor'
            ]
            
            for param in numeric_params:
                current_value = current_params[param]
                target_value = target_params[param]
                interpolated_value = current_value + (target_value - current_value) * self.transition_params['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.transition_params['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.transition_params['transition_progress']*100:.1f}%)"
            interpolated_params['duration'] = target_params['duration']
            
            return interpolated_params
            
        except Exception as e:
            print(f"✗ 插值季节参数获取失败: {e}")
            return self.seasons[self.current_season].copy()
            
    def get_seasonal_events(self, season: str = None) -> List[str]:
        """
        获取季节性事件
        
        Args:
            season: 季节名称（如果为None，则返回当前季节事件）
            
        Returns:
            季节性事件列表
        """
        try:
            if season is None:
                season = self.current_season
                
            return self.seasonal_events.get(season, []).copy()
            
        except Exception as e:
            print(f"✗ 季节性事件获取失败: {e}")
            return []
            
    def add_seasonal_event(self, season: str, event: str):
        """
        添加季节性事件
        
        Args:
            season: 季节名称
            event: 事件名称
        """
        try:
            if season in self.seasonal_events:
                if event not in self.seasonal_events[season]:
                    self.seasonal_events[season].append(event)
                    print(f"✓ 季节性事件已添加: {season} - {event}")
                else:
                    print(f"✗ 事件已存在: {event}")
            else:
                print(f"✗ 无效的季节: {season}")
                
        except Exception as e:
            print(f"✗ 季节性事件添加失败: {e}")
            
    def remove_seasonal_event(self, season: str, event: str):
        """
        移除季节性事件
        
        Args:
            season: 季节名称
            event: 事件名称
        """
        try:
            if season in self.seasonal_events and event in self.seasonal_events[season]:
                self.seasonal_events[season].remove(event)
                print(f"✓ 季节性事件已移除: {season} - {event}")
            else:
                print(f"✗ 事件不存在: {season} - {event}")
                
        except Exception as e:
            print(f"✗ 季节性事件移除失败: {e}")
            
    def get_animal_behavior_factor(self, behavior: str) -> float:
        """
        获取动物行为因子
        
        Args:
            behavior: 行为类型
            
        Returns:
            行为因子 (0.0-1.0)
        """
        try:
            if behavior in self.animal_behaviors and self.current_season in self.animal_behaviors[behavior]:
                return self.animal_behaviors[behavior][self.current_season]
            return 0.5
            
        except Exception as e:
            print(f"✗ 动物行为因子获取失败: {e}")
            return 0.5
            
    def get_vegetation_change_factor(self, change_type: str) -> float:
        """
        获取植被变化因子
        
        Args:
            change_type: 变化类型
            
        Returns:
            变化因子 (0.0-1.0)
        """
        try:
            if change_type in self.vegetation_changes and self.current_season in self.vegetation_changes[change_type]:
                if change_type == 'leaf_color':
                    # 颜色返回RGB元组
                    return self.vegetation_changes[change_type][self.current_season]
                else:
                    # 其他因子返回数值
                    return self.vegetation_changes[change_type][self.current_season]
            return 0.5 if change_type != 'leaf_color' else (0.5, 0.5, 0.5)
            
        except Exception as e:
            print(f"✗ 植被变化因子获取失败: {e}")
            return 0.5 if change_type != 'leaf_color' else (0.5, 0.5, 0.5)
            
    def set_time_config(self, config: Dict[str, float]):
        """
        设置时间配置
        
        Args:
            config: 时间配置字典
        """
        try:
            self.time_config.update(config)
            print(f"✓ 时间配置已更新: {self.time_config}")
        except Exception as e:
            print(f"✗ 时间配置更新失败: {e}")
            
    def get_time_config(self) -> Dict[str, float]:
        """
        获取时间配置
        
        Returns:
            时间配置字典
        """
        return self.time_config.copy()
        
    def set_transition_duration(self, duration: float):
        """
        设置过渡持续时间
        
        Args:
            duration: 持续时间(天)
        """
        try:
            self.transition_params['duration'] = max(0.1, duration)
            print(f"✓ 过渡持续时间设置为: {duration} 天")
        except Exception as e:
            print(f"✗ 过渡持续时间设置失败: {e}")
            
    def get_transition_progress(self) -> float:
        """
        获取季节过渡进度
        
        Returns:
            过渡进度 (0.0-1.0)
        """
        return self.transition_params['transition_progress']
        
    def is_transition_active(self) -> bool:
        """
        检查是否正在进行季节过渡
        
        Returns:
            是否正在进行季节过渡
        """
        return self.transition_params['transition_active']
        
    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 get_season_stats(self) -> Dict[str, Any]:
        """
        获取季节统计信息
        
        Returns:
            统计信息字典
        """
        return self.season_stats.copy()
        
    def reset_season_stats(self):
        """重置季节统计信息"""
        try:
            self.season_stats = {
                'seasons_passed': 0,
                'transitions_completed': 0,
                'events_triggered': 0,
                'total_simulation_time': 0.0
            }
            print("✓ 季节统计信息已重置")
        except Exception as e:
            print(f"✗ 季节统计信息重置失败: {e}")
            
    def fast_forward_to_season(self, target_season: str):
        """
        快进到目标季节
        
        Args:
            target_season: 目标季节
        """
        try:
            if target_season not in self.seasons:
                print(f"✗ 无效的目标季节: {target_season}")
                return
                
            # 直接设置季节
            self.current_season = target_season
            self.season_day = 0
            self.season_progress = 0.0
            
            # 重置过渡状态
            self.transition_params['transition_active'] = False
            self.transition_params['transition_progress'] = 0.0
            
            print(f"✓ 快进到季节: {self.seasons[target_season]['name']}")
            
            # 触发季节事件
            self._trigger_seasonal_events()
            
            # 通知其他系统
            self._notify_systems_of_season_change()
            
        except Exception as e:
            print(f"✗ 快进到季节失败: {e}")