"""
季节系统
负责管理季节变化、季节效果和季节对环境的影响
"""

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

class SeasonSystem:
    """
    季节系统
    负责管理季节变化、季节效果和季节对环境的影响
    """
    
    def __init__(self, plugin):
        """
        初始化季节系统
        
        Args:
            plugin: 天气和季节系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 季节配置
        self.seasons = {
            'spring': {
                'name': '春季',
                'description': '万物复苏的季节',
                'temperature_range': (5.0, 20.0),
                'vegetation_growth': 0.7,
                'flower_bloom': 0.8,
                'day_length_variation': 2.0,  # 日长变化(小时)
                'weather_influence': {
                    'rain': 1.5,
                    'storm': 1.2,
                    'fog': 1.1
                },
                'color_palette': {
                    'foliage': (0.3, 0.7, 0.3),
                    'sky': (0.5, 0.7, 1.0),
                    'overall': (1.0, 1.0, 0.8)
                },
                'transition_duration': 7.0  # 过渡持续时间(天)
            },
            'summer': {
                'name': '夏季',
                'description': '炎热的季节',
                'temperature_range': (20.0, 35.0),
                'vegetation_growth': 1.0,
                'flower_bloom': 0.6,
                'day_length_variation': 4.0,
                'weather_influence': {
                    'rain': 1.0,
                    'storm': 1.5,
                    'fog': 0.5
                },
                'color_palette': {
                    'foliage': (0.2, 0.8, 0.2),
                    'sky': (0.3, 0.6, 1.0),
                    'overall': (1.0, 0.9, 0.7)
                },
                'transition_duration': 7.0
            },
            'autumn': {
                'name': '秋季',
                'description': '收获的季节',
                'temperature_range': (0.0, 20.0),
                'vegetation_growth': 0.5,
                'flower_bloom': 0.2,
                'day_length_variation': 0.0,
                'weather_influence': {
                    'rain': 1.2,
                    'storm': 1.1,
                    'fog': 1.3
                },
                'color_palette': {
                    'foliage': (0.8, 0.5, 0.2),
                    'sky': (0.6, 0.7, 0.9),
                    'overall': (1.0, 0.8, 0.6)
                },
                'transition_duration': 7.0
            },
            'winter': {
                'name': '冬季',
                'description': '寒冷的季节',
                'temperature_range': (-15.0, 5.0),
                'vegetation_growth': 0.1,
                'flower_bloom': 0.0,
                'day_length_variation': -3.0,
                'weather_influence': {
                    'rain': 0.5,
                    'snow': 2.0,
                    'fog': 1.5
                },
                'color_palette': {
                    'foliage': (0.7, 0.7, 0.7),
                    'sky': (0.7, 0.7, 0.8),
                    'overall': (0.8, 0.8, 1.0)
                },
                'transition_duration': 7.0
            }
        }
        
        # 当前季节状态
        self.current_season = 'spring'
        self.season_progress = 0.0  # 季节进度(0-1)
        self.season_day = 0         # 当前季节中的天数
        
        # 季节效果
        self.seasonal_effects = {
            'vegetation_state': 0.0,    # 植被状态(0-1)
            'flower_bloom': 0.0,        # 花朵盛开(0-1)
            'leaf_color': (0.5, 0.5, 0.5),  # 叶子颜色
            'water_temperature': 10.0,  # 水温(°C)
            'animal_activity': 0.5      # 动物活动(0-1)
        }
        
        # 季节时间配置
        self.days_per_season = 90  # 每个季节的天数
        self.season_cycle_enabled = True
        self.season_transition_active = False
        self.transition_progress = 0.0
        
        # 季节活动和事件
        self.seasonal_events = {
            'spring': ['植树节', '春分', '复活节'],
            'summer': ['夏至', '独立日', '暑假'],
            'autumn': ['秋分', '万圣节', '感恩节'],
            'winter': ['冬至', '圣诞节', '新年']
        }
        
        # 季节更新配置
        self.update_interval = 60.0  # 更新间隔(秒)
        self.last_update_time = 0.0
        
        # 统计信息
        self.stats = {
            'seasons_passed': 0,
            'transitions_completed': 0,
            'events_occurred': 0,
            'total_season_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.last_update_time += dt
            if self.last_update_time < self.update_interval:
                return
                
            # 重置更新计时器
            self.last_update_time = 0.0
            
            # 更新季节进度
            self._update_season_progress(dt)
            
            # 更新季节效果
            self._update_seasonal_effects()
            
            # 检查季节事件
            self._check_seasonal_events()
            
            # 更新统计信息
            self.stats['total_season_time'] += dt
            
        except Exception as e:
            print(f"✗ 季节系统更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_season_progress(self, dt: float):
        """
        更新季节进度
        
        Args:
            dt: 时间增量
        """
        try:
            # 假设1秒代表1小时游戏时间
            hours_passed = dt / 1.0
            days_passed = hours_passed / 24.0
            
            # 更新当前季节中的天数
            self.season_day += days_passed
            
            # 更新季节进度
            self.season_progress = min(1.0, self.season_day / self.days_per_season)
            
            # 检查是否需要切换季节
            if self.season_day >= self.days_per_season and self.season_cycle_enabled:
                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:
            self.season_transition_active = True
            self.transition_progress = 0.0
            self.target_season = target_season
            
            print(f"✓ 开始季节过渡: {self.seasons[self.current_season]['name']} -> {self.seasons[target_season]['name']}")
            
        except Exception as e:
            print(f"✗ 季节过渡启动失败: {e}")
            
    def _update_seasonal_effects(self):
        """更新季节效果"""
        try:
            current_season_data = self.seasons[self.current_season]
            
            # 更新植被状态
            self.seasonal_effects['vegetation_state'] = current_season_data['vegetation_growth']
            
            # 更新花朵盛开
            self.seasonal_effects['flower_bloom'] = current_season_data['flower_bloom']
            
            # 更新叶子颜色
            self.seasonal_effects['leaf_color'] = current_season_data['color_palette']['foliage']
            
            # 更新水温（简化模型）
            temp_range = current_season_data['temperature_range']
            avg_temp = (temp_range[0] + temp_range[1]) / 2
            self.seasonal_effects['water_temperature'] = max(0.0, avg_temp * 0.7)
            
            # 更新动物活动
            # 春季和夏季动物活动较高
            if self.current_season in ['spring', 'summer']:
                self.seasonal_effects['animal_activity'] = 0.8
            else:
                self.seasonal_effects['animal_activity'] = 0.3
                
        except Exception as e:
            print(f"✗ 季节效果更新失败: {e}")
            
    def _check_seasonal_events(self):
        """检查季节事件"""
        try:
            # 在实际实现中，这里会检查是否有季节性事件发生
            # 例如：根据日期触发特殊事件
            
            # 简化实现：随机触发事件
            if random.random() < 0.001:  # 很低的概率
                events = self.seasonal_events[self.current_season]
                if events:
                    event = random.choice(events)
                    print(f"✓ 季节事件发生: {event}")
                    self.stats['events_occurred'] += 1
                    
        except Exception as e:
            print(f"✗ 季节事件检查失败: {e}")
            
    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 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_seasonal_effects(self) -> Dict[str, Any]:
        """
        获取当前季节效果
        
        Returns:
            季节效果字典
        """
        return self.seasonal_effects.copy()
        
    def get_season_progress(self) -> float:
        """
        获取季节进度
        
        Returns:
            季节进度(0-1)
        """
        return self.season_progress
        
    def get_season_day(self) -> int:
        """
        获取当前季节中的天数
        
        Returns:
            当前季节中的天数
        """
        return int(self.season_day)
        
    def set_days_per_season(self, days: int):
        """
        设置每个季节的天数
        
        Args:
            days: 天数
        """
        if days > 0:
            self.days_per_season = 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_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_interpolated_season_params(self) -> Dict[str, Any]:
        """
        获取插值后的季节参数（考虑季节过渡）
        
        Returns:
            插值后的季节参数字典
        """
        try:
            if not self.season_transition_active or self.transition_progress <= 0.0:
                # 没有过渡，返回当前季节参数
                return self.seasons[self.current_season].copy()
                
            if self.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 = ['vegetation_growth', 'flower_bloom', 'day_length_variation']
            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_progress
                interpolated_params[param] = interpolated_value
                
            # 对温度范围进行插值
            current_temp_range = current_params['temperature_range']
            target_temp_range = target_params['temperature_range']
            interpolated_temp_range = (
                current_temp_range[0] + (target_temp_range[0] - current_temp_range[0]) * self.transition_progress,
                current_temp_range[1] + (target_temp_range[1] - current_temp_range[1]) * self.transition_progress
            )
            interpolated_params['temperature_range'] = interpolated_temp_range
            
            # 复制其他参数（使用目标季节的参数）
            interpolated_params['name'] = f"{current_params['name']} → {target_params['name']}"
            interpolated_params['description'] = f"过渡季节 ({self.transition_progress*100:.1f}%)"
            interpolated_params['weather_influence'] = target_params['weather_influence']
            interpolated_params['color_palette'] = target_params['color_palette']
            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_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 set_update_interval(self, interval: float):
        """
        设置更新间隔
        
        Args:
            interval: 更新间隔(秒)
        """
        self.update_interval = max(1.0, interval)
        print(f"✓ 季节更新间隔设置为: {interval} 秒")
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'seasons_passed': 0,
            'transitions_completed': 0,
            'events_occurred': 0,
            'total_season_time': 0.0
        }
        print("✓ 季节系统统计信息已重置")
        
    def is_transition_active(self) -> bool:
        """
        检查是否正在进行季节过渡
        
        Returns:
            是否正在进行季节过渡
        """
        return self.season_transition_active
        
    def get_transition_progress(self) -> float:
        """
        获取季节过渡进度
        
        Returns:
            季节过渡进度(0-1)
        """
        return self.transition_progress