"""
植被管理器
负责管理植被类型、分布和基本属性
"""

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

class VegetationManager:
    """
    植被管理器
    负责管理植被类型、分布、属性和基本操作
    """
    
    def __init__(self, plugin):
        """
        初始化植被管理器
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 植被类型定义
        self.vegetation_types = {
            'grass': {
                'name': '草地',
                'description': '低矮的草本植物',
                'height_range': (0.1, 0.5),
                'width_range': (0.1, 0.3),
                'color': (0.2, 0.8, 0.2),
                'growth_rate': 0.1,
                'lifespan': 365,  # 天
                'reproduction_rate': 0.05,
                'preferred_conditions': {
                    'temperature': (10, 30),
                    'humidity': (40, 80),
                    'soil_fertility': (0.3, 1.0)
                },
                'competition_factor': 0.2,
                'resource_consumption': {
                    'water': 0.1,
                    'nutrients': 0.05
                }
            },
            'bush': {
                'name': '灌木',
                'description': '中等高度的木本植物',
                'height_range': (0.5, 2.0),
                'width_range': (0.5, 1.5),
                'color': (0.3, 0.6, 0.3),
                'growth_rate': 0.05,
                'lifespan': 1095,  # 3年
                'reproduction_rate': 0.02,
                'preferred_conditions': {
                    'temperature': (5, 25),
                    'humidity': (30, 70),
                    'soil_fertility': (0.4, 1.0)
                },
                'competition_factor': 0.5,
                'resource_consumption': {
                    'water': 0.3,
                    'nutrients': 0.2
                }
            },
            'tree': {
                'name': '树木',
                'description': '高大的木本植物',
                'height_range': (5.0, 30.0),
                'width_range': (2.0, 10.0),
                'color': (0.1, 0.5, 0.1),
                'growth_rate': 0.01,
                'lifespan': 10950,  # 30年
                'reproduction_rate': 0.005,
                'preferred_conditions': {
                    'temperature': (0, 30),
                    'humidity': (40, 90),
                    'soil_fertility': (0.5, 1.0)
                },
                'competition_factor': 0.8,
                'resource_consumption': {
                    'water': 1.0,
                    'nutrients': 0.5
                }
            },
            'flower': {
                'name': '花卉',
                'description': '开花植物',
                'height_range': (0.1, 1.0),
                'width_range': (0.1, 0.5),
                'color': (0.9, 0.3, 0.8),
                'growth_rate': 0.2,
                'lifespan': 180,  # 半年
                'reproduction_rate': 0.1,
                'preferred_conditions': {
                    'temperature': (15, 25),
                    'humidity': (50, 80),
                    'soil_fertility': (0.6, 1.0)
                },
                'competition_factor': 0.1,
                'resource_consumption': {
                    'water': 0.05,
                    'nutrients': 0.03
                }
            },
            'fern': {
                'name': '蕨类植物',
                'description': '喜阴湿的古老植物',
                'height_range': (0.2, 1.5),
                'width_range': (0.2, 1.0),
                'color': (0.2, 0.6, 0.2),
                'growth_rate': 0.08,
                'lifespan': 730,  # 2年
                'reproduction_rate': 0.03,
                'preferred_conditions': {
                    'temperature': (10, 20),
                    'humidity': (70, 100),
                    'soil_fertility': (0.4, 0.8)
                },
                'competition_factor': 0.3,
                'resource_consumption': {
                    'water': 0.4,
                    'nutrients': 0.1
                }
            },
            'cactus': {
                'name': '仙人掌',
                'description': '耐旱的多肉植物',
                'height_range': (0.1, 3.0),
                'width_range': (0.1, 1.0),
                'color': (0.2, 0.5, 0.2),
                'growth_rate': 0.005,
                'lifespan': 5475,  # 15年
                'reproduction_rate': 0.01,
                'preferred_conditions': {
                    'temperature': (20, 40),
                    'humidity': (10, 30),
                    'soil_fertility': (0.1, 0.5)
                },
                'competition_factor': 0.1,
                'resource_consumption': {
                    'water': 0.01,
                    'nutrients': 0.02
                }
            },
            'moss': {
                'name': '苔藓',
                'description': '低等植物，喜阴湿',
                'height_range': (0.01, 0.1),
                'width_range': (0.05, 0.3),
                'color': (0.3, 0.5, 0.3),
                'growth_rate': 0.15,
                'lifespan': 365,  # 1年
                'reproduction_rate': 0.08,
                'preferred_conditions': {
                    'temperature': (5, 20),
                    'humidity': (80, 100),
                    'soil_fertility': (0.1, 0.6)
                },
                'competition_factor': 0.1,
                'resource_consumption': {
                    'water': 0.2,
                    'nutrients': 0.01
                }
            },
            'vine': {
                'name': '藤蔓',
                'description': '攀援植物',
                'height_range': (1.0, 10.0),
                'width_range': (0.1, 0.5),
                'color': (0.2, 0.7, 0.2),
                'growth_rate': 0.12,
                'lifespan': 730,  # 2年
                'reproduction_rate': 0.06,
                'preferred_conditions': {
                    'temperature': (15, 30),
                    'humidity': (60, 90),
                    'soil_fertility': (0.3, 0.8)
                },
                'competition_factor': 0.4,
                'resource_consumption': {
                    'water': 0.2,
                    'nutrients': 0.1
                }
            }
        }
        
        # 当前植被实例
        self.vegetation_instances = {}
        self.instance_counter = 0
        
        # 植被分布配置
        self.distribution_config = {
            'density': 1.0,  # 植被密度
            'clumping_factor': 0.7,  # 聚集因子
            'random_seed': 12345,  # 随机种子
            'spawn_area': ((-100, -100), (100, 100))  # 生成区域
        }
        
        # 环境影响因子
        self.environment_factors = {
            'temperature': 20.0,
            'humidity': 60.0,
            'soil_fertility': 0.5,
            'light_level': 0.8,
            'water_level': 0.6
        }
        
        # 统计信息
        self.stats = {
            'total_vegetation': 0,
            'vegetation_by_type': {},
            'total_growth_cycles': 0,
            'total_reproductions': 0
        }
        
        print("✓ 植被管理器已创建")
        
    def initialize(self) -> bool:
        """
        初始化植被管理器
        
        Returns:
            是否初始化成功
        """
        try:
            # 初始化统计数据
            self.stats['vegetation_by_type'] = {vt: 0 for vt in self.vegetation_types.keys()}
            
            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.vegetation_instances.clear()
            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.stats['total_growth_cycles'] += 1
            
        except Exception as e:
            print(f"✗ 植被管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_vegetation_types(self) -> List[str]:
        """
        获取所有植被类型
        
        Returns:
            植被类型列表
        """
        return list(self.vegetation_types.keys())
        
    def get_vegetation_info(self, vegetation_type: str) -> Optional[Dict[str, Any]]:
        """
        获取植被类型信息
        
        Args:
            vegetation_type: 植被类型
            
        Returns:
            植被信息字典或None
        """
        return self.vegetation_types.get(vegetation_type)
        
    def create_vegetation_instance(self, vegetation_type: str, position: tuple, 
                                 initial_age: float = 0.0, initial_health: float = 1.0) -> int:
        """
        创建植被实例
        
        Args:
            vegetation_type: 植被类型
            position: 位置坐标 (x, y, z)
            initial_age: 初始年龄
            initial_health: 初始健康度 (0.0-1.0)
            
        Returns:
            植被实例ID
        """
        try:
            if vegetation_type not in self.vegetation_types:
                print(f"✗ 无效的植被类型: {vegetation_type}")
                return -1
                
            instance_id = self.instance_counter
            self.instance_counter += 1
            
            # 获取植被类型信息
            veg_info = self.vegetation_types[vegetation_type]
            
            # 创建实例数据
            instance_data = {
                'id': instance_id,
                'type': vegetation_type,
                'position': position,
                'age': initial_age,
                'health': initial_health,
                'size': self._calculate_initial_size(vegetation_type, initial_age),
                'alive': True,
                'creation_time': time.time(),
                'last_update': time.time()
            }
            
            # 存储实例
            self.vegetation_instances[instance_id] = instance_data
            
            # 更新统计数据
            self.stats['total_vegetation'] += 1
            self.stats['vegetation_by_type'][vegetation_type] += 1
            
            print(f"✓ 植被实例已创建: {veg_info['name']} (ID: {instance_id})")
            return instance_id
            
        except Exception as e:
            print(f"✗ 植被实例创建失败: {e}")
            import traceback
            traceback.print_exc()
            return -1
            
    def _calculate_initial_size(self, vegetation_type: str, age: float) -> float:
        """
        计算初始大小
        
        Args:
            vegetation_type: 植被类型
            age: 年龄
            
        Returns:
            大小比例 (0.0-1.0)
        """
        try:
            veg_info = self.vegetation_types[vegetation_type]
            max_age = veg_info['lifespan']
            
            # 简单的生长模型
            if max_age > 0:
                size_ratio = min(1.0, age / max_age)
                return size_ratio
            return 0.1
            
        except Exception as e:
            print(f"✗ 初始大小计算失败: {e}")
            return 0.1
            
    def remove_vegetation_instance(self, instance_id: int) -> bool:
        """
        移除植被实例
        
        Args:
            instance_id: 植被实例ID
            
        Returns:
            是否移除成功
        """
        try:
            if instance_id not in self.vegetation_instances:
                print(f"✗ 植被实例不存在: {instance_id}")
                return False
                
            instance_data = self.vegetation_instances[instance_id]
            vegetation_type = instance_data['type']
            
            # 移除实例
            del self.vegetation_instances[instance_id]
            
            # 更新统计数据
            self.stats['total_vegetation'] -= 1
            self.stats['vegetation_by_type'][vegetation_type] -= 1
            
            print(f"✓ 植被实例已移除: ID {instance_id}")
            return True
            
        except Exception as e:
            print(f"✗ 植被实例移除失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def get_vegetation_instance(self, instance_id: int) -> Optional[Dict[str, Any]]:
        """
        获取植被实例信息
        
        Args:
            instance_id: 植被实例ID
            
        Returns:
            植被实例信息或None
        """
        return self.vegetation_instances.get(instance_id)
        
    def get_all_vegetation_instances(self) -> Dict[int, Dict[str, Any]]:
        """
        获取所有植被实例
        
        Returns:
            所有植被实例字典
        """
        return self.vegetation_instances.copy()
        
    def update_vegetation_health(self, instance_id: int, health_change: float):
        """
        更新植被健康度
        
        Args:
            instance_id: 植被实例ID
            health_change: 健康度变化值
        """
        try:
            if instance_id not in self.vegetation_instances:
                return
                
            instance = self.vegetation_instances[instance_id]
            new_health = max(0.0, min(1.0, instance['health'] + health_change))
            instance['health'] = new_health
            
            # 如果健康度为0，植物死亡
            if new_health <= 0.0:
                instance['alive'] = False
                print(f"✓ 植被实例死亡: ID {instance_id}")
                
        except Exception as e:
            print(f"✗ 植被健康度更新失败: {e}")
            
    def update_environment_factors(self, factors: Dict[str, float]):
        """
        更新环境因子
        
        Args:
            factors: 环境因子字典
        """
        self.environment_factors.update(factors)
        print(f"✓ 环境因子已更新: {factors}")
        
    def get_environment_factors(self) -> Dict[str, float]:
        """
        获取环境因子
        
        Returns:
            环境因子字典
        """
        return self.environment_factors.copy()
        
    def get_suitability_score(self, vegetation_type: str) -> float:
        """
        计算植被类型的适宜性评分
        
        Args:
            vegetation_type: 植被类型
            
        Returns:
            适宜性评分 (0.0-1.0)
        """
        try:
            if vegetation_type not in self.vegetation_types:
                return 0.0
                
            veg_info = self.vegetation_types[vegetation_type]
            preferred = veg_info['preferred_conditions']
            
            # 计算各环境因子的适宜性
            temperature_suitability = self._calculate_factor_suitability(
                self.environment_factors['temperature'],
                preferred['temperature']
            )
            
            humidity_suitability = self._calculate_factor_suitability(
                self.environment_factors['humidity'],
                preferred['humidity']
            )
            
            fertility_suitability = self._calculate_factor_suitability(
                self.environment_factors['soil_fertility'] * 100,
                (preferred['soil_fertility'][0] * 100, preferred['soil_fertility'][1] * 100)
            )
            
            # 综合评分
            overall_suitability = (
                temperature_suitability * 0.4 +
                humidity_suitability * 0.4 +
                fertility_suitability * 0.2
            )
            
            return max(0.0, min(1.0, overall_suitability))
            
        except Exception as e:
            print(f"✗ 适宜性评分计算失败: {e}")
            return 0.0
            
    def _calculate_factor_suitability(self, current_value: float, preferred_range: tuple) -> float:
        """
        计算单个环境因子的适宜性
        
        Args:
            current_value: 当前值
            preferred_range: 适宜范围 (min, max)
            
        Returns:
            适宜性评分 (0.0-1.0)
        """
        min_val, max_val = preferred_range
        
        if min_val <= current_value <= max_val:
            return 1.0
        elif current_value < min_val:
            # 线性递减到0
            if min_val > 0:
                return max(0.0, 1.0 - (min_val - current_value) / min_val)
            return 0.0
        else:  # current_value > max_val
            # 线性递减到0
            if max_val > 0:
                return max(0.0, 1.0 - (current_value - max_val) / max_val)
            return 0.0
            
    def set_distribution_config(self, config: Dict[str, Any]):
        """
        设置分布配置
        
        Args:
            config: 配置字典
        """
        self.distribution_config.update(config)
        print(f"✓ 分布配置已更新: {self.distribution_config}")
        
    def get_distribution_config(self) -> Dict[str, Any]:
        """
        获取分布配置
        
        Returns:
            分布配置字典
        """
        return self.distribution_config.copy()
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'total_vegetation': 0,
            'vegetation_by_type': {vt: 0 for vt in self.vegetation_types.keys()},
            'total_growth_cycles': 0,
            'total_reproductions': 0
        }
        print("✓ 植被管理器统计信息已重置")