"""
生长模拟器
负责模拟植被的生长、繁殖和死亡过程
"""

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

class GrowthSimulator:
    """
    生长模拟器
    负责模拟植被的生长、繁殖、死亡和生命周期过程
    """
    
    def __init__(self, plugin):
        """
        初始化生长模拟器
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 生长模型参数
        self.growth_models = {
            'exponential': {
                'name': '指数生长',
                'description': '快速增长后趋于稳定',
                'formula': 'size = max_size * (1 - exp(-rate * time))'
            },
            'logistic': {
                'name': '逻辑生长',
                'description': 'S型生长曲线',
                'formula': 'size = max_size / (1 + exp(-rate * (time - midpoint)))'
            },
            'linear': {
                'name': '线性生长',
                'description': '恒定速率生长',
                'formula': 'size = rate * time'
            },
            'seasonal': {
                'name': '季节性生长',
                'description': '受季节影响的生长',
                'formula': 'size = base_rate * (1 + amplitude * sin(frequency * time + phase))'
            }
        }
        
        # 默认生长参数
        self.default_growth_params = {
            'model': 'logistic',             # 默认生长模型
            'base_rate': 0.1,                # 基础生长速率
            'max_size': 1.0,                 # 最大尺寸
            'optimal_conditions': {          # 最佳生长条件
                'temperature': (15, 30),
                'humidity': (50, 80),
                'light': (0.6, 1.0),
                'nutrients': (0.5, 1.0)
            },
            'stress_factors': {              # 压力因子
                'drought_tolerance': 0.3,
                'cold_tolerance': 0.2,
                'heat_tolerance': 0.2,
                'shade_tolerance': 0.4
            }
        }
        
        # 繁殖参数
        self.reproduction_params = {
            'rate': 0.05,                    # 繁殖速率
            'method': 'seeds',               # 繁殖方式: 'seeds', 'sprouting', 'spores'
            'dispersal_distance': 10.0,      # 传播距离
            'seasonal_factor': 1.0,          # 季节性因子
            'competition_radius': 2.0        # 竞争半径
        }
        
        # 死亡参数
        self.mortality_params = {
            'natural_lifespan': 365,         # 自然寿命(天)
            'stress_mortality': 0.01,        # 压力导致的死亡率
            'disease_factor': 0.05,          # 疾病因子
            'competition_factor': 0.1        # 竞争因子
        }
        
        # 环境影响因子
        self.environment_impacts = {
            'temperature_impact': 1.0,
            'humidity_impact': 1.0,
            'light_impact': 1.0,
            'nutrient_impact': 1.0,
            'pollution_impact': 0.0
        }
        
        # 生长阶段定义
        self.growth_stages = {
            'seedling': {
                'name': '幼苗期',
                'size_range': (0.0, 0.2),
                'duration': 30,              # 天
                'vulnerability': 0.8
            },
            'juvenile': {
                'name': '幼年期',
                'size_range': (0.2, 0.5),
                'duration': 90,
                'vulnerability': 0.5
            },
            'mature': {
                'name': '成熟期',
                'size_range': (0.5, 0.9),
                'duration': 180,
                'vulnerability': 0.2
            },
            'old_age': {
                'name': '老年期',
                'size_range': (0.9, 1.0),
                'duration': 90,
                'vulnerability': 0.4
            }
        }
        
        # 时间配置
        self.time_config = {
            'simulation_speed': 1.0,         # 模拟速度
            'update_interval': 60.0,         # 更新间隔(秒)
            'last_update': 0.0
        }
        
        # 统计信息
        self.growth_stats = {
            'total_growth_cycles': 0,
            'successful_reproductions': 0,
            'natural_deaths': 0,
            'stress_deaths': 0,
            'average_growth_rate': 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['last_update'] += dt
            
            # 检查是否需要更新
            if self.time_config['last_update'] >= self.time_config['update_interval']:
                # 执行生长更新
                self._update_growth(dt)
                
                # 重置更新计时器
                self.time_config['last_update'] = 0.0
                
        except Exception as e:
            print(f"✗ 生长模拟器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_growth(self, dt: float):
        """
        更新植被生长
        
        Args:
            dt: 时间增量
        """
        try:
            if not self.plugin.vegetation_manager:
                return
                
            # 获取所有植被实例
            instances = self.plugin.vegetation_manager.get_all_vegetation_instances()
            
            for instance_id, instance in instances.items():
                if not instance['alive']:
                    continue
                    
                # 获取植被类型信息
                veg_type = instance['type']
                veg_info = self.plugin.vegetation_manager.get_vegetation_info(veg_type)
                
                if not veg_info:
                    continue
                    
                # 计算环境影响
                environment_factors = self.plugin.vegetation_manager.get_environment_factors()
                environmental_modifier = self._calculate_environmental_modifier(veg_type, environment_factors)
                
                # 更新年龄
                age_increase = dt / 86400 * self.time_config['simulation_speed']  # 转换为天
                instance['age'] += age_increase
                
                # 计算生长速率
                growth_rate = veg_info['growth_rate'] * environmental_modifier
                
                # 更新大小
                size_increase = growth_rate * dt / 86400
                instance['size'] = min(1.0, instance['size'] + size_increase)
                
                # 更新健康度
                health_change = self._calculate_health_change(instance, veg_info, environment_factors)
                self.plugin.vegetation_manager.update_vegetation_health(instance_id, health_change)
                
                # 检查是否应该繁殖
                if random.random() < veg_info['reproduction_rate'] * dt / 3600:  # 每小时检查
                    self._attempt_reproduction(instance_id, instance)
                    
                # 检查是否应该死亡
                if self._should_die(instance, veg_info):
                    self.plugin.vegetation_manager.remove_vegetation_instance(instance_id)
                    self.growth_stats['natural_deaths'] += 1
                    
            # 更新统计信息
            self.growth_stats['total_growth_cycles'] += 1
            
        except Exception as e:
            print(f"✗ 生长更新失败: {e}")
            
    def _calculate_environmental_modifier(self, veg_type: str, environment_factors: Dict[str, float]) -> float:
        """
        计算环境影响因子
        
        Args:
            veg_type: 植被类型
            environment_factors: 环境因子
            
        Returns:
            环境影响因子 (0.0-2.0)
        """
        try:
            if veg_type not in self.plugin.vegetation_manager.vegetation_types:
                return 1.0
                
            veg_info = self.plugin.vegetation_manager.vegetation_types[veg_type]
            preferred_conditions = veg_info['preferred_conditions']
            
            # 计算各因子的适宜性
            temperature_suitability = self._calculate_suitability(
                environment_factors['temperature'],
                preferred_conditions['temperature']
            )
            
            humidity_suitability = self._calculate_suitability(
                environment_factors['humidity'],
                preferred_conditions['humidity']
            )
            
            # 综合环境影响因子
            modifier = (temperature_suitability + humidity_suitability) / 2.0
            
            # 应用环境影响
            for factor, impact in self.environment_impacts.items():
                modifier *= (1.0 + impact * 0.1)  # 轻微影响
                
            return max(0.0, min(2.0, modifier))
            
        except Exception as e:
            print(f"✗ 环境影响因子计算失败: {e}")
            return 1.0
            
    def _calculate_suitability(self, current_value: float, preferred_range: tuple) -> float:
        """
        计算环境因子适宜性
        
        Args:
            current_value: 当前值
            preferred_range: 偏好范围
            
        Returns:
            适宜性评分 (0.0-1.0)
        """
        try:
            min_val, max_val = preferred_range
            
            if min_val <= current_value <= max_val:
                return 1.0
            elif current_value < min_val:
                if min_val > 0:
                    return max(0.0, 1.0 - (min_val - current_value) / min_val)
                return 0.0
            else:  # current_value > max_val
                if max_val > 0:
                    return max(0.0, 1.0 - (current_value - max_val) / max_val)
                return 0.0
                
        except Exception as e:
            print(f"✗ 适宜性计算失败: {e}")
            return 0.5
            
    def _calculate_health_change(self, instance: Dict[str, Any], veg_info: Dict[str, Any], 
                               environment_factors: Dict[str, float]) -> float:
        """
        计算健康度变化
        
        Args:
            instance: 植被实例
            veg_info: 植被信息
            environment_factors: 环境因子
            
        Returns:
            健康度变化值
        """
        try:
            health_change = 0.0
            
            # 基于年龄的影响
            age_factor = self._calculate_age_factor(instance['age'], veg_info['lifespan'])
            health_change += age_factor
            
            # 基于环境的压力
            stress_factor = self._calculate_stress_factor(environment_factors, veg_info)
            health_change += stress_factor
            
            # 自然恢复
            health_change += 0.001  # 缓慢恢复
            
            return max(-0.1, min(0.1, health_change))
            
        except Exception as e:
            print(f"✗ 健康度变化计算失败: {e}")
            return 0.0
            
    def _calculate_age_factor(self, age: float, lifespan: float) -> float:
        """
        计算年龄因子对健康的影响
        
        Args:
            age: 年龄
            lifespan: 寿命
            
        Returns:
            年龄因子
        """
        try:
            if lifespan <= 0:
                return 0.0
                
            age_ratio = age / lifespan
            
            # 幼年期增长，成年期稳定，老年期下降
            if age_ratio < 0.2:  # 幼年期
                return 0.02  # 快速增长
            elif age_ratio < 0.8:  # 成年期
                return 0.005  # 缓慢增长
            else:  # 老年期
                return -0.03  # 快速下降
                
        except Exception as e:
            print(f"✗ 年龄因子计算失败: {e}")
            return 0.0
            
    def _calculate_stress_factor(self, environment_factors: Dict[str, float], veg_info: Dict[str, Any]) -> float:
        """
        计算环境压力因子
        
        Args:
            environment_factors: 环境因子
            veg_info: 植被信息
            
        Returns:
            压力因子
        """
        try:
            stress = 0.0
            
            # 温度压力
            temp = environment_factors['temperature']
            preferred_temp = veg_info['preferred_conditions']['temperature']
            if temp < preferred_temp[0] or temp > preferred_temp[1]:
                stress -= 0.01
                
            # 湿度压力
            humidity = environment_factors['humidity']
            preferred_humidity = veg_info['preferred_conditions']['humidity']
            if humidity < preferred_humidity[0] or humidity > preferred_humidity[1]:
                stress -= 0.01
                
            # 光照压力
            light = environment_factors['light_level']
            # 假设光照适宜范围是0.5-1.0
            if light < 0.5:
                stress -= 0.005
                
            return stress
            
        except Exception as e:
            print(f"✗ 压力因子计算失败: {e}")
            return 0.0
            
    def _should_die(self, instance: Dict[str, Any], veg_info: Dict[str, Any]) -> bool:
        """
        判断植被是否应该死亡
        
        Args:
            instance: 植被实例
            veg_info: 植被信息
            
        Returns:
            是否应该死亡
        """
        try:
            # 年龄导致的死亡
            if instance['age'] > veg_info['lifespan']:
                return True
                
            # 健康度过低导致的死亡
            if instance['health'] <= 0.0:
                return True
                
            # 压力导致的死亡
            stress_death_probability = 0.001 * (1.0 - instance['health'])
            if random.random() < stress_death_probability:
                return True
                
            return False
            
        except Exception as e:
            print(f"✗ 死亡判断失败: {e}")
            return False
            
    def _attempt_reproduction(self, parent_id: int, parent_instance: Dict[str, Any]):
        """
        尝试繁殖
        
        Args:
            parent_id: 父代ID
            parent_instance: 父代实例
        """
        try:
            if not self.plugin.vegetation_manager:
                return
                
            # 检查繁殖条件
            if parent_instance['health'] < 0.3:  # 健康度过低无法繁殖
                return
                
            if parent_instance['size'] < 0.2:  # 太小无法繁殖
                return
                
            # 计算繁殖位置（在父代附近）
            parent_pos = parent_instance['position']
            dispersal_distance = self.reproduction_params['dispersal_distance']
            
            angle = random.uniform(0, 2 * math.pi)
            distance = random.uniform(0, dispersal_distance)
            
            new_x = parent_pos[0] + distance * math.cos(angle)
            new_z = parent_pos[2] + distance * math.sin(angle)
            
            # 检查竞争
            if self._check_competition(new_x, new_z):
                return
                
            # 创建新实例
            new_instance_id = self.plugin.vegetation_manager.create_vegetation_instance(
                parent_instance['type'],
                (new_x, parent_pos[1], new_z),
                initial_age=0.0,
                initial_health=0.5
            )
            
            if new_instance_id >= 0:
                self.growth_stats['successful_reproductions'] += 1
                
        except Exception as e:
            print(f"✗ 繁殖尝试失败: {e}")
            
    def _check_competition(self, x: float, z: float) -> bool:
        """
        检查新位置的竞争情况
        
        Args:
            x: X坐标
            z: Z坐标
            
        Returns:
            是否存在竞争
        """
        try:
            if not self.plugin.vegetation_manager:
                return False
                
            instances = self.plugin.vegetation_manager.get_all_vegetation_instances()
            competition_radius = self.reproduction_params['competition_radius']
            
            for instance in instances.values():
                if not instance['alive']:
                    continue
                    
                instance_x, _, instance_z = instance['position']
                distance = math.sqrt((x - instance_x)**2 + (z - instance_z)**2)
                
                if distance < competition_radius:
                    return True  # 存在竞争
                    
            return False
            
        except Exception as e:
            print(f"✗ 竞争检查失败: {e}")
            return False
            
    def get_growth_models(self) -> Dict[str, Dict[str, str]]:
        """
        获取生长模型
        
        Returns:
            生长模型字典
        """
        return self.growth_models.copy()
        
    def set_growth_model(self, model: str):
        """
        设置生长模型
        
        Args:
            model: 模型名称
        """
        try:
            if model in self.growth_models:
                self.default_growth_params['model'] = model
                print(f"✓ 生长模型设置为: {self.growth_models[model]['name']}")
            else:
                print(f"✗ 无效的生长模型: {model}")
                
        except Exception as e:
            print(f"✗ 生长模型设置失败: {e}")
            
    def set_growth_parameter(self, parameter: str, value: Any):
        """
        设置生长参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.default_growth_params:
                self.default_growth_params[parameter] = value
                print(f"✓ 生长参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的生长参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 生长参数设置失败: {e}")
            
    def get_growth_parameters(self) -> Dict[str, Any]:
        """
        获取生长参数
        
        Returns:
            生长参数字典
        """
        return self.default_growth_params.copy()
        
    def set_reproduction_parameter(self, parameter: str, value: Any):
        """
        设置繁殖参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.reproduction_params:
                self.reproduction_params[parameter] = value
                print(f"✓ 繁殖参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的繁殖参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 繁殖参数设置失败: {e}")
            
    def get_reproduction_parameters(self) -> Dict[str, Any]:
        """
        获取繁殖参数
        
        Returns:
            繁殖参数字典
        """
        return self.reproduction_params.copy()
        
    def set_mortality_parameter(self, parameter: str, value: Any):
        """
        设置死亡参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.mortality_params:
                self.mortality_params[parameter] = value
                print(f"✓ 死亡参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的死亡参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 死亡参数设置失败: {e}")
            
    def get_mortality_parameters(self) -> Dict[str, Any]:
        """
        获取死亡参数
        
        Returns:
            死亡参数字典
        """
        return self.mortality_params.copy()
        
    def set_environment_impact(self, factor: str, impact: float):
        """
        设置环境影响因子
        
        Args:
            factor: 影响因子名称
            impact: 影响值
        """
        try:
            if factor in self.environment_impacts:
                self.environment_impacts[factor] = impact
                print(f"✓ 环境影响因子已设置: {factor} = {impact}")
            else:
                print(f"✗ 无效的环境影响因子: {factor}")
                
        except Exception as e:
            print(f"✗ 环境影响因子设置失败: {e}")
            
    def get_environment_impacts(self) -> Dict[str, float]:
        """
        获取环境影响因子
        
        Returns:
            环境影响因子字典
        """
        return self.environment_impacts.copy()
        
    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 get_growth_stats(self) -> Dict[str, Any]:
        """
        获取生长统计信息
        
        Returns:
            生长统计信息字典
        """
        return self.growth_stats.copy()
        
    def reset_growth_stats(self):
        """重置生长统计信息"""
        try:
            self.growth_stats = {
                'total_growth_cycles': 0,
                'successful_reproductions': 0,
                'natural_deaths': 0,
                'stress_deaths': 0,
                'average_growth_rate': 0.0
            }
            print("✓ 生长统计信息已重置")
        except Exception as e:
            print(f"✗ 生长统计信息重置失败: {e}")
            
    def simulate_seasonal_growth(self, season: str) -> float:
        """
        模拟季节性生长
        
        Args:
            season: 季节名称
            
        Returns:
            季节性生长修正因子
        """
        try:
            seasonal_factors = {
                'spring': 1.5,   # 春季生长旺盛
                'summer': 1.2,   # 夏季生长良好
                'autumn': 0.8,   # 秋季生长减缓
                'winter': 0.3    # 冬季生长缓慢
            }
            
            return seasonal_factors.get(season, 1.0)
            
        except Exception as e:
            print(f"✗ 季节性生长模拟失败: {e}")
            return 1.0