"""
程序化地形生成插件
为EG引擎提供完整的程序化地形生成和编辑功能
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from core.terrain_manager import TerrainManager
from generators.heightmap_generator import HeightmapGenerator
from noise.noise_generator import NoiseGenerator
from biomes.biome_generator import BiomeGenerator
from erosion.erosion_processor import ErosionProcessor
from vegetation.vegetation_generator import VegetationGenerator
from rendering.terrain_renderer import TerrainRenderer
from utils.terrain_utils import TerrainUtils
from serialization.terrain_serializer import TerrainSerializer

class ProceduralTerrainGenerationPlugin:
    """
    程序化地形生成插件主类
    整合所有地形生成和编辑功能模块
    """
    
    def __init__(self, engine):
        """
        初始化程序化地形生成插件
        
        Args:
            engine: EG引擎实例
        """
        self.engine = engine
        self.name = "ProceduralTerrainGeneration"
        self.version = "1.0.0"
        self.author = "EG Plugin System"
        
        # 功能模块
        self.terrain_manager = None
        self.heightmap_generator = None
        self.noise_generator = None
        self.biome_generator = None
        self.erosion_processor = None
        self.vegetation_generator = None
        self.terrain_renderer = None
        self.terrain_utils = None
        self.terrain_serializer = None
        
        # 新增的编辑器模块
        self.terrain_editor = None
        self.preset_manager = None
        
        # 插件状态
        self.enabled = False
        self.initialized = False
        
        # 性能统计
        self.stats = {
            'terrains_generated': 0,
            'terrains_rendered': 0,
            'generation_time': 0.0,
            'rendering_time': 0.0
        }
        
        print(f"✓ 程序化地形生成插件 v{self.version} 已创建")
        
    def initialize(self) -> bool:
        """
        初始化插件
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化程序化地形生成插件...")
            
            # 初始化核心组件
            self.terrain_manager = TerrainManager(self)
            self.heightmap_generator = HeightmapGenerator(self)
            self.noise_generator = NoiseGenerator(self)
            self.biome_generator = BiomeGenerator(self)
            self.erosion_processor = ErosionProcessor(self)
            self.vegetation_generator = VegetationGenerator(self)
            self.terrain_renderer = TerrainRenderer(self)
            self.terrain_utils = TerrainUtils(self)
            self.terrain_serializer = TerrainSerializer(self)
            
            # 初始化新增的编辑器组件
            from .editor.terrain_editor import TerrainEditor
            from .editor.preset_manager import PresetManager
            
            self.terrain_editor = TerrainEditor(self)
            self.preset_manager = PresetManager(self)
            
            # 初始化各个模块
            modules = [
                self.terrain_manager,
                self.heightmap_generator,
                self.noise_generator,
                self.biome_generator,
                self.erosion_processor,
                self.vegetation_generator,
                self.terrain_renderer,
                self.terrain_utils,
                self.terrain_serializer,
                self.terrain_editor,
                self.preset_manager
            ]
            
            for module in modules:
                if module and not module.initialize():
                    print(f"✗ 模块初始化失败: {module.__class__.__name__}")
                    return False
                    
            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
                
            print("正在启用程序化地形生成插件...")
            
            # 启用各个模块
            modules = [
                self.terrain_manager,
                self.heightmap_generator,
                self.noise_generator,
                self.biome_generator,
                self.erosion_processor,
                self.vegetation_generator,
                self.terrain_renderer,
                self.terrain_utils,
                self.terrain_serializer,
                self.terrain_editor,
                self.preset_manager
            ]
            
            for module in modules:
                if module and not module.enable():
                    print(f"✗ 模块启用失败: {module.__class__.__name__}")
                    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:
            if not self.enabled:
                return
                
            print("正在禁用程序化地形生成插件...")
            
            # 禁用各个模块
            modules = [
                self.terrain_manager,
                self.heightmap_generator,
                self.noise_generator,
                self.biome_generator,
                self.erosion_processor,
                self.vegetation_generator,
                self.terrain_renderer,
                self.terrain_utils,
                self.terrain_serializer,
                self.terrain_editor,
                self.preset_manager
            ]
            
            for module in modules:
                if module:
                    module.disable()
                    
            self.enabled = False
            print("✓ 程序化地形生成插件已禁用")
            
        except Exception as e:
            print(f"✗ 程序化地形生成插件禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理插件资源"""
        try:
            print("正在清理程序化地形生成插件资源...")
            
            # 清理各个模块
            modules = [
                self.terrain_manager,
                self.heightmap_generator,
                self.noise_generator,
                self.biome_generator,
                self.erosion_processor,
                self.vegetation_generator,
                self.terrain_renderer,
                self.terrain_utils,
                self.terrain_serializer,
                self.terrain_editor,
                self.preset_manager
            ]
            
            for module in modules:
                if module:
                    module.finalize()
                    
            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
                
            # 更新各个模块
            modules = [
                self.terrain_manager,
                self.heightmap_generator,
                self.noise_generator,
                self.biome_generator,
                self.erosion_processor,
                self.vegetation_generator,
                self.terrain_renderer,
                self.terrain_utils,
                self.terrain_serializer,
                self.terrain_editor,
                self.preset_manager
            ]
            
            for module in modules:
                if module:
                    module.update(dt)
                    
        except Exception as e:
            print(f"✗ 程序化地形生成插件更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def generate_terrain(self, width: int = None, height: int = None, seed: int = None) -> bool:
        """
        生成地形
        
        Args:
            width: 地形宽度
            height: 地形高度
            seed: 随机种子
            
        Returns:
            是否生成成功
        """
        try:
            if not self.enabled:
                print("✗ 插件未启用")
                return False
                
            if self.terrain_manager:
                return self.terrain_manager.generate_terrain(width, height, seed)
            return False
            
        except Exception as e:
            print(f"✗ 地形生成失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def set_seed(self, seed: int):
        """
        设置随机种子
        
        Args:
            seed: 随机种子
        """
        self.config['seed'] = seed
        if self.noise_generator:
            self.noise_generator.set_seed(seed)
        if self.heightmap_generator:
            self.heightmap_generator.set_seed(seed)
        print(f"✓ 随机种子设置为: {seed}")
        
    def set_terrain_size(self, size: int):
        """
        设置地形大小
        
        Args:
            size: 地形大小
        """
        self.config['terrain_size'] = size
        print(f"✓ 地形大小设置为: {size}")
        
    def set_height_scale(self, scale: float):
        """
        设置高度缩放
        
        Args:
            scale: 高度缩放因子
        """
        self.config['height_scale'] = scale
        print(f"✓ 高度缩放设置为: {scale}")
        
    def get_terrain_data(self) -> dict:
        """
        获取地形数据
        
        Returns:
            地形数据字典
        """
        if self.terrain_manager:
            return self.terrain_manager.get_terrain_data()
        return {}
        
    def save_terrain(self, filename: str) -> bool:
        """
        保存地形到文件
        
        Args:
            filename: 文件名
            
        Returns:
            是否保存成功
        """
        try:
            if self.terrain_serializer:
                return self.terrain_serializer.save_terrain(filename)
            return False
        except Exception as e:
            print(f"✗ 地形保存失败: {e}")
            return False
            
    def load_terrain(self, filename: str) -> bool:
        """
        从文件加载地形
        
        Args:
            filename: 文件名
            
        Returns:
            是否加载成功
        """
        try:
            if self.terrain_serializer:
                return self.terrain_serializer.load_terrain(filename)
            return False
        except Exception as e:
            print(f"✗ 地形加载失败: {e}")
            return False

# 插件注册信息
def get_plugin_info():
    """获取插件信息"""
    return {
        'name': 'procedural_terrain_generation',
        'version': '1.0.0',
        'author': 'EG Team',
        'description': '程序化地形生成插件，提供高性能的程序化地形生成功能',
        'dependencies': []
    }

# 创建插件实例的工厂函数
def create_plugin(world):
    """创建插件实例"""
    return ProceduralTerrainGenerationPlugin(world)