"""
生态编辑器
提供可视化界面用于编辑和调整生态系统参数
"""

import time
from typing import Dict, Any, List, Optional
import json

class EcoEditor:
    """
    生态编辑器
    提供可视化界面用于编辑和调整生态系统参数，包括植被、动物、环境等
    """
    
    def __init__(self, plugin):
        """
        初始化生态编辑器
        
        Args:
            plugin: 植被和生态系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 编辑器配置
        self.editor_config = {
            'auto_preview': True,
            'realtime_update': True,
            'preview_quality': 'medium',
            'history_limit': 50,
            'snap_to_grid': True,
            'grid_size': 1.0
        }
        
        # 编辑模式
        self.edit_modes = {
            'vegetation': {'name': '植被编辑', 'description': '编辑植被参数和分布'},
            'animals': {'name': '动物编辑', 'description': '编辑动物种群和行为'},
            'environment': {'name': '环境编辑', 'description': '编辑环境因子和地形影响'},
            'ecosystem': {'name': '生态系统编辑', 'description': '编辑生态系统参数和关系'},
            'seasons': {'name': '季节编辑', 'description': '编辑季节参数和效果'},
            'interactions': {'name': '交互编辑', 'description': '编辑生态系统交互参数'},
            'visualization': {'name': '可视化编辑', 'description': '编辑可视化效果参数'}
        }
        
        self.current_edit_mode = 'vegetation'
        
        # 参数分组
        self.parameter_groups = {
            'vegetation': ['growth_rate', 'reproduction_rate', 'preferred_conditions', 'competition_factor'],
            'animals': ['reproduction_rate', 'mortality_rate', 'mobility', 'preferred_food', 'territory_size'],
            'environment': ['temperature', 'humidity', 'soil_fertility', 'light_level', 'water_level'],
            'ecosystem': ['biodiversity_index', 'stability_index', 'productivity_rate', 'carrying_capacity'],
            'seasons': ['season_duration', 'temperature_modifier', 'growth_factor', 'light_duration'],
            'interactions': ['herbivory_rate', 'seed_dispersal_rate', 'pollination_rate', 'competition_intensity'],
            'visualization': ['render_distance', 'effect_intensity', 'color_scheme', 'transparency']
        }
        
        # 编辑历史
        self.edit_history = []
        self.history_position = -1
        
        # 选择系统
        self.selected_objects = []
        self.selection_mode = 'single'  # 'single', 'multiple', 'area'
        
        # 工具系统
        self.tools = {
            'select': {'name': '选择工具', 'description': '选择和编辑对象'},
            'spawn': {'name': '生成工具', 'description': '生成植被或动物'},
            'paint': {'name': '绘制工具', 'description': '绘制植被分布'},
            'erase': {'name': '擦除工具', 'description': '擦除植被或动物'},
            'modify': {'name': '修改工具', 'description': '修改对象属性'},
            'analyze': {'name': '分析工具', 'description': '分析生态系统状态'}
        }
        
        self.current_tool = 'select'
        
        # 预览数据
        self.preview_data = None
        self.preview_dirty = False
        
        # 工具状态
        self.is_editing = False
        self.selected_parameter = None
        
        # 分析数据
        self.analysis_data = {
            'last_analysis': None,
            'analysis_timestamp': 0,
            'analysis_results': {}
        }
        
        # 统计信息
        self.stats = {
            'edits_made': 0,
            'undos_performed': 0,
            'redos_performed': 0,
            'total_edit_time': 0.0,
            'average_edit_time': 0.0,
            'objects_selected': 0
        }
        
        # UI组件引用（在实际实现中会连接到GUI）
        self.ui_components = {
            'toolbar': None,
            'properties_panel': None,
            'preview_window': None,
            'parameter_sliders': None,
            'history_panel': None,
            'selection_info': None,
            'analysis_panel': None
        }
        
        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
                
            # 更新预览
            if self.preview_dirty and self.editor_config['auto_preview']:
                self._update_preview()
                
            # 处理实时更新
            if self.editor_config['realtime_update']:
                self._handle_realtime_updates()
                
        except Exception as e:
            print(f"✗ 生态编辑器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_preview(self):
        """更新预览显示"""
        try:
            # 在实际实现中，这里会更新预览窗口
            self.preview_dirty = False
        except Exception as e:
            print(f"✗ 预览更新失败: {e}")
            
    def _handle_realtime_updates(self):
        """处理实时更新"""
        try:
            # 在实际实现中，这里会处理实时编辑更新
            pass
        except Exception as e:
            print(f"✗ 实时更新处理失败: {e}")
            
    def set_edit_mode(self, mode: str):
        """
        设置编辑模式
        
        Args:
            mode: 编辑模式
        """
        if mode in self.edit_modes:
            self.current_edit_mode = mode
            print(f"✓ 编辑模式设置为: {self.edit_modes[mode]['name']}")
        else:
            print(f"✗ 无效的编辑模式: {mode}")
            
    def get_edit_modes(self) -> Dict[str, Dict[str, str]]:
        """
        获取可用的编辑模式
        
        Returns:
            编辑模式字典
        """
        return self.edit_modes.copy()
        
    def get_current_edit_mode(self) -> str:
        """
        获取当前编辑模式
        
        Returns:
            当前编辑模式
        """
        return self.current_edit_mode
        
    def set_parameter(self, parameter_name: str, value: Any):
        """
        设置参数值
        
        Args:
            parameter_name: 参数名称
            value: 参数值
        """
        try:
            # 保存当前状态到历史记录
            self._save_state_to_history()
            
            # 根据编辑模式应用参数
            if self.current_edit_mode == 'vegetation' and self.plugin.vegetation_manager:
                # 处理植被参数
                veg_types = self.plugin.vegetation_manager.get_vegetation_types()
                for veg_type in veg_types:
                    veg_info = self.plugin.vegetation_manager.get_vegetation_info(veg_type)
                    if veg_info and parameter_name in veg_info:
                        # 在实际实现中会更新植被参数
                        pass
                        
            elif self.current_edit_mode == 'animals' and self.plugin.animal_simulator:
                # 处理动物参数
                animal_species = self.plugin.animal_simulator.get_animal_species()
                for species in animal_species:
                    animal_info = self.plugin.animal_simulator.get_animal_info(species)
                    if animal_info and parameter_name in animal_info:
                        # 在实际实现中会更新动物参数
                        pass
                        
            elif self.current_edit_mode == 'environment' and self.plugin.vegetation_manager:
                # 处理环境参数
                env_factors = self.plugin.vegetation_manager.get_environment_factors()
                if parameter_name in env_factors:
                    env_factors[parameter_name] = value
                    self.plugin.vegetation_manager.update_environment_factors(env_factors)
                    
            elif self.current_edit_mode == 'ecosystem' and self.plugin.ecosystem_manager:
                # 处理生态系统参数
                self.plugin.ecosystem_manager.set_ecosystem_parameter(parameter_name, value)
                
            elif self.current_edit_mode == 'seasons' and self.plugin.seasonal_effects:
                # 处理季节参数
                if parameter_name == 'season_duration':
                    current_season = self.plugin.seasonal_effects.get_current_season()
                    self.plugin.seasonal_effects.set_season_duration(current_season, value)
                    
            elif self.current_edit_mode == 'interactions' and self.plugin.ecosystem_interactions:
                # 处理交互参数
                self.plugin.ecosystem_interactions.set_interaction_parameter(parameter_name, value)
                
            elif self.current_edit_mode == 'visualization':
                # 处理可视化参数
                if self.plugin.eco_visualizer:
                    # 处理基础可视化参数
                    pass
                    
                if self.plugin.advanced_visuals:
                    # 处理高级可视化参数
                    if parameter_name in ['render_distance', 'effect_intensity', 'transparency']:
                        config = self.plugin.advanced_visuals.get_visualization_config()
                        config[parameter_name] = value
                        self.plugin.advanced_visuals.set_visualization_config(config)
                    elif parameter_name == 'color_scheme':
                        self.plugin.advanced_visuals.set_color_scheme(value)
                        
            # 标记预览需要更新
            self.preview_dirty = True
            
            # 更新统计信息
            self.stats['edits_made'] += 1
            
            print(f"✓ 参数 '{parameter_name}' 设置为: {value}")
            
        except Exception as e:
            print(f"✗ 参数设置失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_parameter(self, parameter_name: str) -> Any:
        """
        获取参数值
        
        Args:
            parameter_name: 参数名称
            
        Returns:
            参数值
        """
        try:
            # 根据编辑模式获取参数
            if self.current_edit_mode == 'vegetation' and self.plugin.vegetation_manager:
                # 获取植被参数
                pass
                
            elif self.current_edit_mode == 'animals' and self.plugin.animal_simulator:
                # 获取动物参数
                pass
                
            elif self.current_edit_mode == 'environment' and self.plugin.vegetation_manager:
                env_factors = self.plugin.vegetation_manager.get_environment_factors()
                return env_factors.get(parameter_name)
                
            elif self.current_edit_mode == 'ecosystem' and self.plugin.ecosystem_manager:
                return self.plugin.ecosystem_manager.get_ecosystem_parameter(parameter_name)
                
            elif self.current_edit_mode == 'seasons' and self.plugin.seasonal_effects:
                if parameter_name == 'season_duration':
                    current_season = self.plugin.seasonal_effects.get_current_season()
                    season_info = self.plugin.seasonal_effects.get_season_info(current_season)
                    if season_info:
                        return season_info.get('duration', 90)
                        
            elif self.current_edit_mode == 'interactions' and self.plugin.ecosystem_interactions:
                params = self.plugin.ecosystem_interactions.get_interaction_parameters()
                return params.get(parameter_name)
                
            elif self.current_edit_mode == 'visualization':
                if self.plugin.advanced_visuals:
                    config = self.plugin.advanced_visuals.get_visualization_config()
                    if parameter_name in config:
                        return config[parameter_name]
                    elif parameter_name == 'color_scheme':
                        return config.get('color_scheme', 'default')
                        
        except Exception as e:
            print(f"✗ 参数获取失败: {e}")
            import traceback
            traceback.print_exc()
            
        return None
        
    def _save_state_to_history(self):
        """保存当前状态到历史记录"""
        try:
            # 创建状态快照
            state_snapshot = {
                'timestamp': time.time(),
                'edit_mode': self.current_edit_mode,
                'vegetation_params': {},
                'animal_params': {},
                'environment_params': {},
                'ecosystem_params': {},
                'season_params': {},
                'interaction_params': {},
                'visualization_params': {}
            }
            
            # 保存植被参数
            if self.plugin.vegetation_manager:
                veg_types = self.plugin.vegetation_manager.get_vegetation_types()
                for veg_type in veg_types:
                    veg_info = self.plugin.vegetation_manager.get_vegetation_info(veg_type)
                    if veg_info:
                        state_snapshot['vegetation_params'][veg_type] = veg_info.copy()
                        
            # 保存动物参数
            if self.plugin.animal_simulator:
                animal_species = self.plugin.animal_simulator.get_animal_species()
                for species in animal_species:
                    animal_info = self.plugin.animal_simulator.get_animal_info(species)
                    if animal_info:
                        state_snapshot['animal_params'][species] = animal_info.copy()
                        
            # 保存环境参数
            if self.plugin.vegetation_manager:
                state_snapshot['environment_params'] = self.plugin.vegetation_manager.get_environment_factors().copy()
                
            # 保存生态系统参数
            if self.plugin.ecosystem_manager:
                state_snapshot['ecosystem_params'] = self.plugin.ecosystem_manager.get_ecosystem_parameters().copy()
                
            # 保存季节参数
            if self.plugin.seasonal_effects:
                current_season = self.plugin.seasonal_effects.get_current_season()
                season_info = self.plugin.seasonal_effects.get_season_info(current_season)
                if season_info:
                    state_snapshot['season_params'] = season_info.copy()
                    
            # 保存交互参数
            if self.plugin.ecosystem_interactions:
                state_snapshot['interaction_params'] = self.plugin.ecosystem_interactions.get_interaction_parameters().copy()
                
            # 保存可视化参数
            if self.plugin.advanced_visuals:
                state_snapshot['visualization_params'] = self.plugin.advanced_visuals.get_visualization_config().copy()
                    
            # 添加到历史记录
            if self.history_position < len(self.edit_history) - 1:
                # 如果当前不在历史记录末尾，截断后续记录
                self.edit_history = self.edit_history[:self.history_position + 1]
                
            self.edit_history.append(state_snapshot)
            self.history_position += 1
            
            # 限制历史记录数量
            if len(self.edit_history) > self.editor_config['history_limit']:
                self.edit_history.pop(0)
                self.history_position -= 1
                
        except Exception as e:
            print(f"✗ 状态保存失败: {e}")
            import traceback
            traceback.print_exc()
            
    def undo(self) -> bool:
        """
        撤销操作
        
        Returns:
            是否撤销成功
        """
        try:
            if not self.enabled:
                print("✗ 生态编辑器未启用")
                return False
                
            if self.history_position <= 0:
                print("✗ 没有可撤销的操作")
                return False
                
            # 移动到前一个历史状态
            self.history_position -= 1
            
            # 恢复状态
            self._restore_state_from_history()
            
            # 更新统计信息
            self.stats['undos_performed'] += 1
            
            print("✓ 撤销操作完成")
            return True
            
        except Exception as e:
            print(f"✗ 撤销操作失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def redo(self) -> bool:
        """
        重做操作
        
        Returns:
            是否重做成功
        """
        try:
            if not self.enabled:
                print("✗ 生态编辑器未启用")
                return False
                
            if self.history_position >= len(self.edit_history) - 1:
                print("✗ 没有可重做的操作")
                return False
                
            # 移动到下一个历史状态
            self.history_position += 1
            
            # 恢复状态
            self._restore_state_from_history()
            
            # 更新统计信息
            self.stats['redos_performed'] += 1
            
            print("✓ 重做操作完成")
            return True
            
        except Exception as e:
            print(f"✗ 重做操作失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def _restore_state_from_history(self):
        """从历史记录恢复状态"""
        try:
            if self.history_position < 0:
                return
                
            # 获取历史状态
            state = self.edit_history[self.history_position]
            
            # 恢复参数
            if self.plugin.vegetation_manager and state['vegetation_params']:
                # 在实际实现中会恢复植被参数
                pass
                
            if self.plugin.animal_simulator and state['animal_params']:
                # 在实际实现中会恢复动物参数
                pass
                
            if self.plugin.vegetation_manager and state['environment_params']:
                self.plugin.vegetation_manager.update_environment_factors(state['environment_params'])
                
            if self.plugin.ecosystem_manager and state['ecosystem_params']:
                for param_name, param_value in state['ecosystem_params'].items():
                    self.plugin.ecosystem_manager.set_ecosystem_parameter(param_name, param_value)
                    
            if self.plugin.seasonal_effects and state['season_params']:
                # 在实际实现中会恢复季节参数
                pass
                
            if self.plugin.ecosystem_interactions and state['interaction_params']:
                # 恢复交互参数
                for param_name, param_value in state['interaction_params'].items():
                    self.plugin.ecosystem_interactions.set_interaction_parameter(param_name, param_value)
                    
            if self.plugin.advanced_visuals and state['visualization_params']:
                # 恢复可视化参数
                self.plugin.advanced_visuals.set_visualization_config(state['visualization_params'])
                
            # 标记预览需要更新
            self.preview_dirty = True
            
        except Exception as e:
            print(f"✗ 状态恢复失败: {e}")
            import traceback
            traceback.print_exc()
            
    def clear_history(self):
        """清空历史记录"""
        try:
            self.edit_history.clear()
            self.history_position = -1
            print("✓ 历史记录已清空")
        except Exception as e:
            print(f"✗ 历史记录清空失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_parameter_groups(self) -> Dict[str, List[str]]:
        """
        获取参数分组
        
        Returns:
            参数分组字典
        """
        return self.parameter_groups.copy()
        
    def get_parameters_in_group(self, group_name: str) -> List[str]:
        """
        获取组中的参数列表
        
        Args:
            group_name: 组名称
            
        Returns:
            参数列表
        """
        return self.parameter_groups.get(group_name, []).copy()
        
    def set_editor_config(self, config: Dict[str, Any]):
        """
        设置编辑器配置
        
        Args:
            config: 配置字典
        """
        self.editor_config.update(config)
        print(f"✓ 编辑器配置已更新: {self.editor_config}")
        
    def get_editor_config(self) -> Dict[str, Any]:
        """
        获取编辑器配置
        
        Returns:
            配置字典
        """
        return self.editor_config.copy()
        
    def set_tool(self, tool_name: str):
        """
        设置当前工具
        
        Args:
            tool_name: 工具名称
        """
        if tool_name in self.tools:
            self.current_tool = tool_name
            print(f"✓ 当前工具设置为: {self.tools[tool_name]['name']}")
        else:
            print(f"✗ 无效的工具: {tool_name}")
            
    def get_tools(self) -> Dict[str, Dict[str, str]]:
        """
        获取可用工具
        
        Returns:
            工具字典
        """
        return self.tools.copy()
        
    def get_current_tool(self) -> str:
        """
        获取当前工具
        
        Returns:
            当前工具名称
        """
        return self.current_tool
        
    def select_object(self, object_id: Any, multi_select: bool = False):
        """
        选择对象
        
        Args:
            object_id: 对象ID
            multi_select: 是否多选
        """
        try:
            if multi_select:
                if object_id not in self.selected_objects:
                    self.selected_objects.append(object_id)
            else:
                self.selected_objects = [object_id]
                
            self.stats['objects_selected'] = len(self.selected_objects)
            print(f"✓ 对象已选择: {object_id}")
            
        except Exception as e:
            print(f"✗ 对象选择失败: {e}")
            
    def deselect_object(self, object_id: Any):
        """
        取消选择对象
        
        Args:
            object_id: 对象ID
        """
        try:
            if object_id in self.selected_objects:
                self.selected_objects.remove(object_id)
                self.stats['objects_selected'] = len(self.selected_objects)
                print(f"✓ 对象已取消选择: {object_id}")
                
        except Exception as e:
            print(f"✗ 对象取消选择失败: {e}")
            
    def clear_selection(self):
        """清空选择"""
        try:
            self.selected_objects.clear()
            self.stats['objects_selected'] = 0
            print("✓ 选择已清空")
        except Exception as e:
            print(f"✗ 选择清空失败: {e}")
            
    def get_selected_objects(self) -> List[Any]:
        """
        获取选中的对象
        
        Returns:
            选中的对象列表
        """
        return self.selected_objects.copy()
        
    def set_selection_mode(self, mode: str):
        """
        设置选择模式
        
        Args:
            mode: 选择模式 ('single', 'multiple', 'area')
        """
        if mode in ['single', 'multiple', 'area']:
            self.selection_mode = mode
            print(f"✓ 选择模式设置为: {mode}")
        else:
            print(f"✗ 无效的选择模式: {mode}")
            
    def get_selection_mode(self) -> str:
        """
        获取选择模式
        
        Returns:
            选择模式
        """
        return self.selection_mode
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        # 更新平均编辑时间
        total_edits = self.stats['edits_made'] + self.stats['undos_performed'] + self.stats['redos_performed']
        if total_edits > 0:
            self.stats['average_edit_time'] = self.stats['total_edit_time'] / total_edits
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'edits_made': 0,
            'undos_performed': 0,
            'redos_performed': 0,
            'total_edit_time': 0.0,
            'average_edit_time': 0.0,
            'objects_selected': 0
        }
        print("✓ 生态编辑器统计信息已重置")
        
    def export_editor_state(self, filename: str) -> bool:
        """
        导出编辑器状态
        
        Args:
            filename: 文件名
            
        Returns:
            是否导出成功
        """
        try:
            # 创建状态数据
            state_data = {
                'editor_config': self.editor_config,
                'current_edit_mode': self.current_edit_mode,
                'current_tool': self.current_tool,
                'parameter_groups': self.parameter_groups,
                'timestamp': time.time()
            }
            
            # 保存为JSON文件
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(state_data, f, ensure_ascii=False, indent=2)
                
            print(f"✓ 编辑器状态已导出到: {filename}")
            return True
            
        except Exception as e:
            print(f"✗ 编辑器状态导出失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def import_editor_state(self, filename: str) -> bool:
        """
        导入编辑器状态
        
        Args:
            filename: 文件名
            
        Returns:
            是否导入成功
        """
        try:
            # 读取JSON文件
            with open(filename, 'r', encoding='utf-8') as f:
                state_data = json.load(f)
                
            # 应用状态
            if 'editor_config' in state_data:
                self.set_editor_config(state_data['editor_config'])
            if 'current_edit_mode' in state_data:
                self.set_edit_mode(state_data['current_edit_mode'])
            if 'current_tool' in state_data:
                self.set_tool(state_data['current_tool'])
                
            print(f"✓ 编辑器状态已从 {filename} 导入")
            return True
            
        except Exception as e:
            print(f"✗ 编辑器状态导入失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def set_ui_component(self, component_name: str, component: Any):
        """
        设置UI组件引用
        
        Args:
            component_name: 组件名称
            component: 组件引用
        """
        if component_name in self.ui_components:
            self.ui_components[component_name] = component
            print(f"✓ UI组件 '{component_name}' 已设置")
        else:
            print(f"✗ 无效的UI组件名称: {component_name}")
            
    def refresh_ui(self):
        """刷新UI显示"""
        try:
            # 在实际实现中，这里会更新所有UI组件的显示
            print("✓ UI刷新完成")
        except Exception as e:
            print(f"✗ UI刷新失败: {e}")
            
    def show_preview_window(self):
        """显示预览窗口"""
        try:
            # 在实际实现中，这里会创建并显示预览窗口
            print("✓ 预览窗口已显示")
        except Exception as e:
            print(f"✗ 预览窗口显示失败: {e}")
            
    def hide_preview_window(self):
        """隐藏预览窗口"""
        try:
            # 在实际实现中，这里会隐藏预览窗口
            print("✓ 预览窗口已隐藏")
        except Exception as e:
            print(f"✗ 预览窗口隐藏失败: {e}")
            
    def update_preview_window(self):
        """更新预览窗口内容"""
        try:
            # 在实际实现中，这里会更新预览窗口的内容
            print("✓ 预览窗口已更新")
        except Exception as e:
            print(f"✗ 预览窗口更新失败: {e}")
            
    def apply_preset(self, preset_name: str):
        """
        应用预设
        
        Args:
            preset_name: 预设名称
        """
        try:
            if self.plugin.preset_manager:
                self.plugin.preset_manager.apply_preset(preset_name)
                self.preview_dirty = True
                print(f"✓ 预设 '{preset_name}' 已应用")
            else:
                print("✗ 预设管理器不可用")
        except Exception as e:
            print(f"✗ 预设应用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def save_current_as_preset(self, preset_name: str, description: str = '') -> str:
        """
        将当前配置保存为预设
        
        Args:
            preset_name: 预设名称
            description: 预设描述
            
        Returns:
            预设ID
        """
        try:
            if self.plugin.preset_manager:
                preset_id = self.plugin.preset_manager.create_terrain_preset_from_current(preset_name, description)
                print(f"✓ 当前配置已保存为预设: {preset_name}")
                return preset_id
            else:
                print("✗ 预设管理器不可用")
                return ''
        except Exception as e:
            print(f"✗ 预设保存失败: {e}")
            import traceback
            traceback.print_exc()
            return ''
            
    def spawn_vegetation(self, vegetation_type: str, position: tuple, count: int = 1):
        """
        生成植被
        
        Args:
            vegetation_type: 植被类型
            position: 位置
            count: 数量
        """
        try:
            if not self.plugin.vegetation_manager:
                print("✗ 植被管理器不可用")
                return
                
            if vegetation_type not in self.plugin.vegetation_manager.get_vegetation_types():
                print(f"✗ 无效的植被类型: {vegetation_type}")
                return
                
            # 保存当前状态到历史记录
            self._save_state_to_history()
            
            spawned_count = 0
            for i in range(count):
                # 添加随机偏移
                if count > 1:
                    offset_x = random.uniform(-2.0, 2.0)
                    offset_z = random.uniform(-2.0, 2.0)
                    spawn_position = (position[0] + offset_x, position[1], position[2] + offset_z)
                else:
                    spawn_position = position
                    
                instance_id = self.plugin.vegetation_manager.create_vegetation_instance(
                    vegetation_type, spawn_position
                )
                
                if instance_id >= 0:
                    spawned_count += 1
                    
            print(f"✓ 已生成 {spawned_count} 个 {vegetation_type}")
            self.stats['edits_made'] += 1
            
        except Exception as e:
            print(f"✗ 植被生成失败: {e}")
            import traceback
            traceback.print_exc()
            
    def remove_selected_objects(self):
        """移除选中的对象"""
        try:
            if not self.plugin.vegetation_manager:
                print("✗ 植被管理器不可用")
                return
                
            # 保存当前状态到历史记录
            self._save_state_to_history()
            
            removed_count = 0
            for obj_id in self.selected_objects:
                # 假设所有选中对象都是植被实例
                if self.plugin.vegetation_manager.remove_vegetation_instance(obj_id):
                    removed_count += 1
                    
            self.clear_selection()
            print(f"✓ 已移除 {removed_count} 个对象")
            self.stats['edits_made'] += 1
            
        except Exception as e:
            print(f"✗ 对象移除失败: {e}")
            import traceback
            traceback.print_exc()
            
    def analyze_ecosystem(self) -> Dict[str, Any]:
        """
        分析生态系统状态
        
        Returns:
            分析结果字典
        """
        try:
            analysis_results = {
                'timestamp': time.time(),
                'biodiversity': 0.0,
                'health_index': 0.0,
                'stability': 0.0,
                'total_species': 0,
                'total_population': 0,
                'resource_availability': 0.0
            }
            
            # 收集生态系统数据
            if self.plugin.ecosystem_manager:
                system_state = self.plugin.ecosystem_manager.get_system_state()
                analysis_results['health_index'] = system_state.get('health_index', 0.0)
                analysis_results['stability'] = self.plugin.ecosystem_manager.get_stability_index()
                analysis_results['biodiversity'] = self.plugin.ecosystem_manager.get_biodiversity_index()
                
            if self.plugin.vegetation_manager:
                veg_stats = self.plugin.vegetation_manager.get_stats()
                analysis_results['total_species'] += len(veg_stats.get('vegetation_by_type', {}))
                analysis_results['total_population'] += veg_stats.get('total_vegetation', 0)
                
            if self.plugin.animal_simulator:
                animal_stats = self.plugin.animal_simulator.get_stats()
                analysis_results['total_species'] += len(animal_stats.get('animals_by_species', {}))
                analysis_results['total_population'] += animal_stats.get('total_animals', 0)
                
            if self.plugin.vegetation_manager:
                env_factors = self.plugin.vegetation_manager.get_environment_factors()
                # 简化的资源可用性计算
                resource_score = (
                    env_factors.get('temperature', 50) / 100 * 0.25 +
                    env_factors.get('humidity', 50) / 100 * 0.25 +
                    env_factors.get('soil_fertility', 0.5) * 0.25 +
                    env_factors.get('water_level', 0.5) * 0.25
                )
                analysis_results['resource_availability'] = resource_score
                
            # 保存分析结果
            self.analysis_data['last_analysis'] = analysis_results
            self.analysis_data['analysis_timestamp'] = analysis_results['timestamp']
            self.analysis_data['analysis_results'] = analysis_results
            
            print("✓ 生态系统分析完成")
            return analysis_results
            
        except Exception as e:
            print(f"✗ 生态系统分析失败: {e}")
            import traceback
            traceback.print_exc()
            return {}
            
    def get_last_analysis(self) -> Optional[Dict[str, Any]]:
        """
        获取上次分析结果
        
        Returns:
            上次分析结果或None
        """
        return self.analysis_data['last_analysis']
        
    def export_analysis_report(self, filename: str) -> bool:
        """
        导出分析报告
        
        Args:
            filename: 文件名
            
        Returns:
            是否导出成功
        """
        try:
            analysis = self.get_last_analysis()
            if not analysis:
                print("✗ 没有可用的分析数据")
                return False
                
            # 创建报告数据
            report_data = {
                'analysis_report': analysis,
                'editor_state': {
                    'edit_mode': self.current_edit_mode,
                    'tool': self.current_tool,
                    'timestamp': time.time()
                }
            }
            
            # 保存为JSON文件
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, ensure_ascii=False, indent=2)
                
            print(f"✓ 分析报告已导出到: {filename}")
            return True
            
        except Exception as e:
            print(f"✗ 分析报告导出失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def toggle_visualization_type(self, visualization_type: str):
        """
        切换可视化类型启用状态
        
        Args:
            visualization_type: 可视化类型
        """
        try:
            if self.plugin.advanced_visuals:
                # 获取当前状态
                vis_types = self.plugin.advanced_visuals.get_visualization_types()
                if visualization_type in vis_types:
                    current_state = vis_types[visualization_type]['enabled']
                    self.plugin.advanced_visuals.set_visualization_type_enabled(visualization_type, not current_state)
                    print(f"✓ 可视化类型 '{visualization_type}' 已{'启用' if not current_state else '禁用'}")
                else:
                    print(f"✗ 无效的可视化类型: {visualization_type}")
            else:
                print("✗ 高级可视化模块不可用")
        except Exception as e:
            print(f"✗ 可视化类型切换失败: {e}")
            
    def capture_visualization_screenshot(self, filename: str = None) -> str:
        """
        捕获可视化截图
        
        Args:
            filename: 文件名
            
        Returns:
            截图文件路径
        """
        try:
            if self.plugin.advanced_visuals:
                return self.plugin.advanced_visuals.capture_visualization_screenshot(filename)
            else:
                print("✗ 高级可视化模块不可用")
                return ""
        except Exception as e:
            print(f"✗ 可视化截图捕获失败: {e}")
            return ""