"""
生态系统管理器
负责管理生态系统整体状态和生态关系
"""

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

class EcosystemManager:
    """
    生态系统管理器
    负责管理生态系统整体状态、生态关系和系统平衡
    """
    
    def __init__(self, plugin):
        """
        初始化生态系统管理器
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 生态关系定义
        self.ecosystem_relationships = {
            'predator_prey': [],  # 捕食者-猎物关系
            'competition': [],    # 竞争关系
            'symbiosis': [],      # 共生关系
            'parasitism': []      # 寄生关系
        }
        
        # 生态位定义
        self.ecological_niches = {
            'primary_producer': {
                'name': '初级生产者',
                'description': '通过光合作用生产有机物',
                'organisms': ['grass', 'bush', 'tree', 'flower', 'fern', 'cactus', 'moss', 'vine']
            },
            'primary_consumer': {
                'name': '初级消费者',
                'description': '以植物为食的动物',
                'organisms': []
            },
            'secondary_consumer': {
                'name': '次级消费者',
                'description': '以初级消费者为食的动物',
                'organisms': []
            },
            'tertiary_consumer': {
                'name': '三级消费者',
                'description': '以次级消费者为食的动物',
                'organisms': []
            },
            'decomposer': {
                'name': '分解者',
                'description': '分解有机物的微生物和真菌',
                'organisms': []
            }
        }
        
        # 食物链层级
        self.trophic_levels = {
            1: {'name': '生产者', 'organisms': []},
            2: {'name': '初级消费者', 'organisms': []},
            3: {'name': '次级消费者', 'organisms': []},
            4: {'name': '三级消费者', 'organisms': []},
            5: {'name': '顶级捕食者', 'organisms': []}
        }
        
        # 生态系统参数
        self.ecosystem_parameters = {
            'biodiversity_index': 0.5,      # 生物多样性指数
            'stability_index': 0.7,         # 系统稳定性指数
            'resilience_index': 0.6,        # 系统恢复力指数
            'productivity_rate': 1.0,       # 生产力比率
            'energy_flow_efficiency': 0.1,  # 能量传递效率
            'carrying_capacity': 1000       # 环境承载能力
        }
        
        # 生态事件
        self.ecological_events = {
            'natural_disaster': {
                'probability': 0.001,  # 每天发生概率
                'effects': {
                    'vegetation_loss': 0.3,
                    'animal_death': 0.2,
                    'soil_degradation': 0.1
                }
            },
            'disease_outbreak': {
                'probability': 0.005,
                'effects': {
                    'population_reduction': 0.2,
                    'growth_inhibition': 0.3
                }
            },
            'invasive_species': {
                'probability': 0.002,
                'effects': {
                    'native_competition': 0.4,
                    'habitat_displacement': 0.3
                }
            }
        }
        
        # 系统状态
        self.system_state = {
            'total_biomass': 0.0,
            'species_count': 0,
            'population_balance': 0.0,
            'resource_availability': 1.0,
            'last_event_time': 0.0
        }
        
        # 时间配置
        self.time_config = {
            'simulation_speed': 1.0,
            'day_length': 24.0,  # 小时
            'current_time': 0.0
        }
        
        # 统计信息
        self.stats = {
            'total_interactions': 0,
            'events_occurred': 0,
            'species_extinctions': 0,
            'new_species_introductions': 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._check_ecological_events(dt)
            
            # 更新系统状态
            self._update_system_state()
            
        except Exception as e:
            print(f"✗ 生态系统管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _check_ecological_events(self, dt: float):
        """
        检查生态事件
        
        Args:
            dt: 时间增量
        """
        try:
            # 计算事件概率（基于时间增量）
            for event_name, event_data in self.ecological_events.items():
                probability = event_data['probability']
                adjusted_probability = 1 - math.pow(1 - probability, dt / 3600)  # 转换为小时
                
                if random.random() < adjusted_probability:
                    self._trigger_ecological_event(event_name)
                    
        except Exception as e:
            print(f"✗ 生态事件检查失败: {e}")
            
    def _trigger_ecological_event(self, event_name: str):
        """
        触发生态事件
        
        Args:
            event_name: 事件名称
        """
        try:
            if event_name not in self.ecological_events:
                return
                
            event_data = self.ecological_events[event_name]
            effects = event_data['effects']
            
            print(f"✓ 生态事件发生: {event_name}")
            
            # 应用事件效果
            if 'vegetation_loss' in effects and self.plugin.vegetation_manager:
                # 减少植被数量
                loss_ratio = effects['vegetation_loss']
                veg_instances = self.plugin.vegetation_manager.get_all_vegetation_instances()
                instances_to_remove = int(len(veg_instances) * loss_ratio)
                
                instance_ids = list(veg_instances.keys())
                for i in range(min(instances_to_remove, len(instance_ids))):
                    instance_id = random.choice(instance_ids)
                    self.plugin.vegetation_manager.remove_vegetation_instance(instance_id)
                    if instance_id in instance_ids:
                        instance_ids.remove(instance_id)
                        
            # 更新统计信息
            self.stats['events_occurred'] += 1
            self.system_state['last_event_time'] = self.time_config['current_time']
            
        except Exception as e:
            print(f"✗ 生态事件触发失败: {e}")
            
    def _update_system_state(self):
        """更新系统状态"""
        try:
            # 计算总生物量
            total_biomass = 0.0
            species_count = 0
            
            if self.plugin.vegetation_manager:
                veg_instances = self.plugin.vegetation_manager.get_all_vegetation_instances()
                for instance in veg_instances.values():
                    if instance['alive']:
                        veg_type = instance['type']
                        veg_info = self.plugin.vegetation_manager.get_vegetation_info(veg_type)
                        if veg_info:
                            # 简单的生物量计算
                            avg_height = (veg_info['height_range'][0] + veg_info['height_range'][1]) / 2
                            total_biomass += avg_height * instance['health'] * instance['size']
                            
                species_count = len(veg_instances)
                
            self.system_state['total_biomass'] = total_biomass
            self.system_state['species_count'] = species_count
            
        except Exception as e:
            print(f"✗ 系统状态更新失败: {e}")
            
    def add_predator_prey_relationship(self, predator: str, prey: str, efficiency: float = 0.1):
        """
        添加捕食者-猎物关系
        
        Args:
            predator: 捕食者
            prey: 猎物
            efficiency: 捕食效率
        """
        try:
            relationship = {
                'predator': predator,
                'prey': prey,
                'efficiency': efficiency,
                'creation_time': time.time()
            }
            
            self.ecosystem_relationships['predator_prey'].append(relationship)
            print(f"✓ 捕食者-猎物关系已添加: {predator} -> {prey}")
            
        except Exception as e:
            print(f"✗ 捕食者-猎物关系添加失败: {e}")
            
    def add_competition_relationship(self, species1: str, species2: str, intensity: float = 0.5):
        """
        添加竞争关系
        
        Args:
            species1: 物种1
            species2: 物种2
            intensity: 竞争强度
        """
        try:
            relationship = {
                'species1': species1,
                'species2': species2,
                'intensity': intensity,
                'creation_time': time.time()
            }
            
            self.ecosystem_relationships['competition'].append(relationship)
            print(f"✓ 竞争关系已添加: {species1} <-> {species2}")
            
        except Exception as e:
            print(f"✗ 竞争关系添加失败: {e}")
            
    def add_symbiosis_relationship(self, species1: str, species2: str, benefit1: float = 0.2, benefit2: float = 0.2):
        """
        添加共生关系
        
        Args:
            species1: 物种1
            species2: 物种2
            benefit1: 物种1获得的益处
            benefit2: 物种2获得的益处
        """
        try:
            relationship = {
                'species1': species1,
                'species2': species2,
                'benefit1': benefit1,
                'benefit2': benefit2,
                'creation_time': time.time()
            }
            
            self.ecosystem_relationships['symbiosis'].append(relationship)
            print(f"✓ 共生关系已添加: {species1} <-> {species2}")
            
        except Exception as e:
            print(f"✗ 共生关系添加失败: {e}")
            
    def get_ecosystem_relationships(self, relationship_type: str = None) -> List[Dict[str, Any]]:
        """
        获取生态系统关系
        
        Args:
            relationship_type: 关系类型（如果为None，则返回所有关系）
            
        Returns:
            关系列表
        """
        try:
            if relationship_type:
                if relationship_type in self.ecosystem_relationships:
                    return self.ecosystem_relationships[relationship_type].copy()
                else:
                    return []
            else:
                all_relationships = []
                for rel_type, relationships in self.ecosystem_relationships.items():
                    all_relationships.extend(relationships)
                return all_relationships
                
        except Exception as e:
            print(f"✗ 生态系统关系获取失败: {e}")
            return []
            
    def remove_ecosystem_relationship(self, relationship_type: str, index: int) -> bool:
        """
        移除生态系统关系
        
        Args:
            relationship_type: 关系类型
            index: 关系索引
            
        Returns:
            是否移除成功
        """
        try:
            if relationship_type not in self.ecosystem_relationships:
                print(f"✗ 无效的关系类型: {relationship_type}")
                return False
                
            if index < 0 or index >= len(self.ecosystem_relationships[relationship_type]):
                print(f"✗ 无效的关系索引: {index}")
                return False
                
            removed_relationship = self.ecosystem_relationships[relationship_type].pop(index)
            print(f"✓ 生态系统关系已移除: {relationship_type} 关系")
            return True
            
        except Exception as e:
            print(f"✗ 生态系统关系移除失败: {e}")
            return False
            
    def add_organism_to_niche(self, niche_name: str, organism: str) -> bool:
        """
        添加生物到生态位
        
        Args:
            niche_name: 生态位名称
            organism: 生物名称
            
        Returns:
            是否添加成功
        """
        try:
            if niche_name not in self.ecological_niches:
                print(f"✗ 无效的生态位: {niche_name}")
                return False
                
            if organism not in self.ecological_niches[niche_name]['organisms']:
                self.ecological_niches[niche_name]['organisms'].append(organism)
                print(f"✓ 生物已添加到生态位: {organism} -> {niche_name}")
                return True
            else:
                print(f"✗ 生物已在生态位中: {organism}")
                return False
                
        except Exception as e:
            print(f"✗ 生物添加到生态位失败: {e}")
            return False
            
    def get_organisms_in_niche(self, niche_name: str) -> List[str]:
        """
        获取生态位中的生物
        
        Args:
            niche_name: 生态位名称
            
        Returns:
            生物列表
        """
        try:
            if niche_name in self.ecological_niches:
                return self.ecological_niches[niche_name]['organisms'].copy()
            return []
            
        except Exception as e:
            print(f"✗ 生态位生物获取失败: {e}")
            return []
            
    def set_ecosystem_parameter(self, parameter: str, value: float):
        """
        设置生态系统参数
        
        Args:
            parameter: 参数名称
            value: 参数值
        """
        try:
            if parameter in self.ecosystem_parameters:
                self.ecosystem_parameters[parameter] = value
                print(f"✓ 生态系统参数已设置: {parameter} = {value}")
            else:
                print(f"✗ 无效的生态系统参数: {parameter}")
                
        except Exception as e:
            print(f"✗ 生态系统参数设置失败: {e}")
            
    def get_ecosystem_parameter(self, parameter: str) -> Optional[float]:
        """
        获取生态系统参数
        
        Args:
            parameter: 参数名称
            
        Returns:
            参数值或None
        """
        return self.ecosystem_parameters.get(parameter)
        
    def get_ecosystem_parameters(self) -> Dict[str, float]:
        """
        获取所有生态系统参数
        
        Returns:
            参数字典
        """
        return self.ecosystem_parameters.copy()
        
    def set_time_config(self, config: Dict[str, float]):
        """
        设置时间配置
        
        Args:
            config: 时间配置字典
        """
        self.time_config.update(config)
        print(f"✓ 时间配置已更新: {self.time_config}")
        
    def get_time_config(self) -> Dict[str, float]:
        """
        获取时间配置
        
        Returns:
            时间配置字典
        """
        return self.time_config.copy()
        
    def get_system_state(self) -> Dict[str, Any]:
        """
        获取系统状态
        
        Returns:
            系统状态字典
        """
        return self.system_state.copy()
        
    def get_biodiversity_index(self) -> float:
        """
        计算生物多样性指数
        
        Returns:
            生物多样性指数 (0.0-1.0)
        """
        try:
            # 简化的多样性计算
            species_count = self.system_state['species_count']
            if species_count > 0:
                # 基于物种数量的简单计算
                normalized_count = min(1.0, species_count / 50.0)  # 假设50个物种为高多样性
                return normalized_count
            return 0.0
            
        except Exception as e:
            print(f"✗ 生物多样性指数计算失败: {e}")
            return 0.0
            
    def get_stability_index(self) -> float:
        """
        计算系统稳定性指数
        
        Returns:
            系统稳定性指数 (0.0-1.0)
        """
        try:
            # 简化的稳定性计算
            time_since_event = self.time_config['current_time'] - self.system_state['last_event_time']
            if time_since_event > 0:
                # 基于事件间隔的时间稳定性
                stability = min(1.0, time_since_event / 86400.0)  # 一天为完全稳定
                return stability
            return 0.5  # 默认中等稳定性
            
        except Exception as e:
            print(f"✗ 系统稳定性指数计算失败: {e}")
            return 0.5
            
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'total_interactions': 0,
            'events_occurred': 0,
            'species_extinctions': 0,
            'new_species_introductions': 0
        }
        print("✓ 生态系统管理器统计信息已重置")
        
    def get_ecological_niches(self) -> Dict[str, Dict[str, Any]]:
        """
        获取生态位信息
        
        Returns:
            生态位字典
        """
        return self.ecological_niches.copy()
        
    def get_trophic_levels(self) -> Dict[int, Dict[str, Any]]:
        """
        获取营养级信息
        
        Returns:
            营养级字典
        """
        return self.trophic_levels.copy()