"""
生态系统动力学
负责模拟生态系统中的复杂动力学过程
"""

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

class EcosystemDynamics:
    """
    生态系统动力学
    负责模拟生态系统中的复杂动力学过程，包括能量流动、物质循环等
    """
    
    def __init__(self, plugin):
        """
        初始化生态系统动力学
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 能量流动模型
        self.energy_flow_model = {
            'primary_production': 1000.0,    # 初级生产力 (单位: 能量/天)
            'trophic_efficiency': 0.1,       # 营养级效率 (10%定律)
            'respiration_loss': 0.2,         # 呼吸损失
            'decomposition_rate': 0.05,      # 分解速率
            'energy_transfer_loss': 0.9      # 能量传递损失
        }
        
        # 物质循环模型
        self.nutrient_cycle_model = {
            'carbon_cycle': {
                'photosynthesis_rate': 0.8,    # 光合作用速率
                'respiration_rate': 0.3,       # 呼吸速率
                'decomposition_rate': 0.1,     # 分解速率
                'ocean_absorption': 0.05       # 海洋吸收速率
            },
            'nitrogen_cycle': {
                'nitrogen_fixation': 0.02,     # 固氮作用
                'nitrification': 0.03,         # 硝化作用
                'denitrification': 0.01,       # 反硝化作用
                'plant_uptake': 0.05           # 植物吸收
            },
            'phosphorus_cycle': {
                'weathering_rate': 0.01,       # 风化速率
                'plant_uptake': 0.02,          # 植物吸收
                'mineralization': 0.015,       # 矿化作用
                'leaching': 0.005              # 流失速率
            }
        }
        
        # 生态系统反馈机制
        self.feedback_mechanisms = {
            'positive_feedback': {
                'description': '增强系统变化的反馈',
                'examples': ['植被增加导致更多降水', '温度升高加速分解']
            },
            'negative_feedback': {
                'description': '抑制系统变化的反馈',
                'examples': ['捕食者增加导致猎物减少', '营养缺乏抑制植物生长']
            }
        }
        
        # 生态系统稳定性指标
        self.stability_indicators = {
            'resilience': 0.7,               # 恢复力
            'resistance': 0.6,               # 抵抗力
            'persistence': 0.8,              # 持续性
            'constancy': 0.5,                # 恒定性
            'predictability': 0.4            # 可预测性
        }
        
        # 系统动态参数
        self.dynamic_parameters = {
            'time_scale': 1.0,               # 时间尺度
            'spatial_scale': 1.0,            # 空间尺度
            'complexity_level': 0.8,         # 复杂度水平
            'stochastic_factor': 0.1         # 随机因子
        }
        
        # 生态系统服务
        self.ecosystem_services = {
            'provisioning': {
                'food': 0.0,
                'water': 0.0,
                'timber': 0.0,
                'fiber': 0.0
            },
            'regulating': {
                'climate_regulation': 0.0,
                'water_regulation': 0.0,
                'disease_regulation': 0.0,
                'pollination': 0.0
            },
            'supporting': {
                'soil_formation': 0.0,
                'nutrient_cycling': 0.0,
                'primary_production': 0.0
            },
            'cultural': {
                'recreation': 0.0,
                'aesthetic': 0.0,
                'education': 0.0,
                'spiritual': 0.0
            }
        }
        
        # 系统状态
        self.system_state = {
            'total_energy': 10000.0,         # 总能量
            'available_nutrients': 500.0,    # 可用营养物质
            'biodiversity_index': 0.6,       # 生物多样性指数
            'stability_index': 0.7,          # 稳定性指数
            'health_index': 0.8              # 健康指数
        }
        
        # 动态过程
        self.dynamic_processes = {
            'succession': {
                'active': True,
                'stage': 'mature',           # 'pioneer', 'intermediate', 'mature', 'climax'
                'progress': 0.8
            },
            'disturbance': {
                'frequency': 0.01,           # 干扰频率
                'intensity': 0.2,            # 干扰强度
                'recovery_time': 365.0       # 恢复时间(天)
            }
        }
        
        # 统计信息
        self.stats = {
            'energy_flows': 0,
            'nutrient_cycles': 0,
            'feedback_events': 0,
            'stability_changes': 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._update_energy_flow(dt)
            
            # 更新物质循环
            self._update_nutrient_cycles(dt)
            
            # 更新系统状态
            self._update_system_state(dt)
            
            # 检查反馈机制
            self._check_feedback_mechanisms(dt)
            
        except Exception as e:
            print(f"✗ 生态系统动力学更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_energy_flow(self, dt: float):
        """
        更新能量流动
        
        Args:
            dt: 时间增量
        """
        try:
            # 模拟光合作用产生的初级生产力
            photosynthesis = self.energy_flow_model['primary_production'] * dt / 86400
            
            # 计算呼吸损失
            respiration_loss = photosynthesis * self.energy_flow_model['respiration_loss']
            
            # 计算净初级生产力
            npp = photosynthesis - respiration_loss
            
            # 更新系统总能量
            energy_loss = self.system_state['total_energy'] * 0.001 * dt / 86400  # 基础能量流失
            self.system_state['total_energy'] += npp - energy_loss
            
            # 更新统计信息
            self.stats['energy_flows'] += 1
            
        except Exception as e:
            print(f"✗ 能量流动更新失败: {e}")
            
    def _update_nutrient_cycles(self, dt: float):
        """
        更新物质循环
        
        Args:
            dt: 时间增量
        """
        try:
            # 更新碳循环
            carbon_change = (
                self.nutrient_cycle_model['carbon_cycle']['photosynthesis_rate'] -
                self.nutrient_cycle_model['carbon_cycle']['respiration_rate'] -
                self.nutrient_cycle_model['carbon_cycle']['decomposition_rate']
            ) * dt / 86400
            
            # 更新氮循环
            nitrogen_change = (
                self.nutrient_cycle_model['nitrogen_cycle']['nitrogen_fixation'] +
                self.nutrient_cycle_model['nitrogen_cycle']['nitrification'] -
                self.nutrient_cycle_model['nitrogen_cycle']['denitrification'] -
                self.nutrient_cycle_model['nitrogen_cycle']['plant_uptake']
            ) * dt / 86400
            
            # 更新磷循环
            phosphorus_change = (
                self.nutrient_cycle_model['phosphorus_cycle']['weathering_rate'] +
                self.nutrient_cycle_model['phosphorus_cycle']['mineralization'] -
                self.nutrient_cycle_model['phosphorus_cycle']['plant_uptake'] -
                self.nutrient_cycle_model['phosphorus_cycle']['leaching']
            ) * dt / 86400
            
            # 更新可用营养物质
            nutrient_change = carbon_change + nitrogen_change + phosphorus_change
            self.system_state['available_nutrients'] = max(0, self.system_state['available_nutrients'] + nutrient_change)
            
            # 更新统计信息
            self.stats['nutrient_cycles'] += 1
            
        except Exception as e:
            print(f"✗ 物质循环更新失败: {e}")
            
    def _update_system_state(self, dt: float):
        """
        更新系统状态
        
        Args:
            dt: 时间增量
        """
        try:
            # 基于植被和动物数量更新生物多样性指数
            if self.plugin.vegetation_manager and self.plugin.animal_simulator:
                veg_count = self.plugin.vegetation_manager.get_stats()['total_vegetation']
                animal_count = self.plugin.animal_simulator.get_stats()['total_animals']
                
                diversity_score = min(1.0, (veg_count + animal_count) / 1000.0)
                self.system_state['biodiversity_index'] = diversity_score
                
            # 更新健康指数
            health_factors = [
                self.system_state['biodiversity_index'],
                min(1.0, self.system_state['available_nutrients'] / 1000.0),
                min(1.0, self.system_state['total_energy'] / 20000.0)
            ]
            
            self.system_state['health_index'] = sum(health_factors) / len(health_factors)
            
        except Exception as e:
            print(f"✗ 系统状态更新失败: {e}")
            
    def _check_feedback_mechanisms(self, dt: float):
        """
        检查反馈机制
        
        Args:
            dt: 时间增量
        """
        try:
            # 检查是否触发正反馈或负反馈
            feedback_probability = self.dynamic_parameters['stochastic_factor']
            if random.random() < feedback_probability * dt / 3600:  # 每小时检查
                feedback_type = random.choice(['positive', 'negative'])
                self._trigger_feedback(feedback_type)
                
        except Exception as e:
            print(f"✗ 反馈机制检查失败: {e}")
            
    def _trigger_feedback(self, feedback_type: str):
        """
        触发反馈机制
        
        Args:
            feedback_type: 反馈类型 ('positive' 或 'negative')
        """
        try:
            print(f"✓ {feedback_type.capitalize()} feedback triggered in ecosystem")
            
            # 根据反馈类型调整系统参数
            if feedback_type == 'positive':
                # 增强系统变化
                self.system_state['total_energy'] *= 1.05
            else:
                # 抑制系统变化
                self.system_state['total_energy'] *= 0.95
                
            # 更新统计信息
            self.stats['feedback_events'] += 1
            
        except Exception as e:
            print(f"✗ 反馈机制触发失败: {e}")
            
    def get_energy_flow_model(self) -> Dict[str, float]:
        """
        获取能量流动模型参数
        
        Returns:
            能量流动模型参数字典
        """
        return self.energy_flow_model.copy()
        
    def get_nutrient_cycle_model(self) -> Dict[str, Dict[str, float]]:
        """
        获取物质循环模型参数
        
        Returns:
            物质循环模型参数字典
        """
        return self.nutrient_cycle_model.copy()
        
    def set_energy_flow_parameter(self, parameter: str, value: float):
        """
        设置能量流动参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.energy_flow_model:
                self.energy_flow_model[parameter] = value
                print(f"✓ 能量流动参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的能量流动参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 能量流动参数设置失败: {e}")
            
    def set_nutrient_cycle_parameter(self, cycle: str, parameter: str, value: float):
        """
        设置物质循环参数
        
        Args:
            cycle: 循环类型 ('carbon_cycle', 'nitrogen_cycle', 'phosphorus_cycle')
            parameter: 参数名称
            value: 参数值
        """
        try:
            if cycle in self.nutrient_cycle_model and parameter in self.nutrient_cycle_model[cycle]:
                self.nutrient_cycle_model[cycle][parameter] = value
                print(f"✓ 物质循环参数已设置: {cycle}.{parameter} = {value}")
            else:
                print(f"✗ 无效的物质循环参数: {cycle}.{parameter}")
                
        except Exception as e:
            print(f"✗ 物质循环参数设置失败: {e}")
            
    def get_system_state(self) -> Dict[str, float]:
        """
        获取系统状态
        
        Returns:
            系统状态字典
        """
        return self.system_state.copy()
        
    def get_stability_indicators(self) -> Dict[str, float]:
        """
        获取稳定性指标
        
        Returns:
            稳定性指标字典
        """
        return self.stability_indicators.copy()
        
    def update_stability_indicator(self, indicator: str, value: float):
        """
        更新稳定性指标
        
        Args:
            indicator: 指标名称
            value: 指标值
        """
        try:
            if indicator in self.stability_indicators:
                self.stability_indicators[indicator] = max(0.0, min(1.0, value))
                self.stats['stability_changes'] += 1
                print(f"✓ 稳定性指标已更新: {indicator} = {value}")
            else:
                print(f"✗ 无效的稳定性指标: {indicator}")
                
        except Exception as e:
            print(f"✗ 稳定性指标更新失败: {e}")
            
    def get_ecosystem_services(self) -> Dict[str, Dict[str, float]]:
        """
        获取生态系统服务
        
        Returns:
            生态系统服务字典
        """
        return self.ecosystem_services.copy()
        
    def calculate_ecosystem_service_value(self, service_category: str, service: str) -> float:
        """
        计算生态系统服务价值
        
        Args:
            service_category: 服务类别
            service: 服务名称
            
        Returns:
            服务价值
        """
        try:
            if service_category in self.ecosystem_services and service in self.ecosystem_services[service_category]:
                base_value = self.ecosystem_services[service_category][service]
                
                # 基于系统健康度调整价值
                health_factor = self.system_state['health_index']
                adjusted_value = base_value * health_factor
                
                return adjusted_value
            return 0.0
            
        except Exception as e:
            print(f"✗ 生态系统服务价值计算失败: {e}")
            return 0.0
            
    def get_dynamic_processes(self) -> Dict[str, Dict[str, Any]]:
        """
        获取动态过程信息
        
        Returns:
            动态过程字典
        """
        return self.dynamic_processes.copy()
        
    def set_dynamic_parameter(self, parameter: str, value: float):
        """
        设置动态参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.dynamic_parameters:
                self.dynamic_parameters[parameter] = value
                print(f"✓ 动态参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的动态参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 动态参数设置失败: {e}")
            
    def get_dynamic_parameters(self) -> Dict[str, float]:
        """
        获取动态参数
        
        Returns:
            动态参数字典
        """
        return self.dynamic_parameters.copy()
        
    def trigger_disturbance(self, intensity: float = 0.5):
        """
        触发干扰事件
        
        Args:
            intensity: 干扰强度 (0.0-1.0)
        """
        try:
            # 减少系统能量和营养物质
            energy_loss = self.system_state['total_energy'] * intensity * 0.3
            nutrient_loss = self.system_state['available_nutrients'] * intensity * 0.2
            
            self.system_state['total_energy'] = max(0, self.system_state['total_energy'] - energy_loss)
            self.system_state['available_nutrients'] = max(0, self.system_state['available_nutrients'] - nutrient_loss)
            
            # 降低健康指数
            self.system_state['health_index'] *= (1.0 - intensity * 0.3)
            
            print(f"✓ 干扰事件已触发，强度: {intensity}")
            
        except Exception as e:
            print(f"✗ 干扰事件触发失败: {e}")
            
    def get_feedback_mechanisms(self) -> Dict[str, Dict[str, Any]]:
        """
        获取反馈机制信息
        
        Returns:
            反馈机制字典
        """
        return self.feedback_mechanisms.copy()
        
    def get_stats(self) -> Dict[str, int]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'energy_flows': 0,
            'nutrient_cycles': 0,
            'feedback_events': 0,
            'stability_changes': 0
        }
        print("✓ 生态系统动力学统计信息已重置")
        
    def calculate_carrying_capacity(self) -> float:
        """
        计算环境承载能力
        
        Returns:
            承载能力值
        """
        try:
            # 基于可用营养物质和能量计算承载能力
            energy_factor = self.system_state['total_energy'] / 10000.0
            nutrient_factor = self.system_state['available_nutrients'] / 500.0
            health_factor = self.system_state['health_index']
            
            carrying_capacity = (energy_factor + nutrient_factor + health_factor) / 3.0
            return max(0.0, min(1.0, carrying_capacity))
            
        except Exception as e:
            print(f"✗ 承载能力计算失败: {e}")
            return 0.5