"""
群体智能插件配置
提供完整的配置管理功能，支持多种数据类型和持久化存储
"""

import json
import os
from pathlib import Path

class Config:
    """
    配置管理类
    支持配置的加载、保存、验证和管理
    """
    
    def __init__(self, config_file=None):
        # 配置文件路径
        self.config_file = config_file or self._get_default_config_path()
        
        # 默认配置
        self.default_settings = {
            # 基本Boids参数
            "cohesion_weight": 1.0,
            "separation_weight": 1.5,
            "alignment_weight": 1.0,
            "perception_radius": 10.0,
            
            # 移动参数
            "max_speed": 5.0,
            "max_acceleration": 1.0,
            "max_force": 0.5,
            
            # 群体参数
            "member_count": 20,
            "swarm_type": "鸟类",
            
            # 行为开关
            "seek_enabled": False,
            "obstacle_avoidance_enabled": True,
            "wander_enabled": False,
            "boundary_enabled": True,
            "predator_avoid_enabled": False,
            "arrival_enabled": False,
            "formation_enabled": False,
            "path_following_enabled": False,
            "interaction_enabled": True,  # 群体间交互开关
            "learning_enabled": False,  # 学习能力开关
            "environment_awareness_enabled": True,  # 环境感知开关
            
            # 高级行为参数
            "personal_space": 2.0,  # 个人空间半径
            "obstacle_radius": 5.0,  # 障碍物影响半径
            "seek_weight": 1.0,  # 寻求力权重
            "flee_weight": 1.0,  # 逃离力权重
            "wander_weight": 0.5,  # 游走力权重
            "wander_radius": 5.0,  # 游走半径
            "wander_distance": 10.0,  # 游走距离
            "wander_jitter": 1.0,  # 游走抖动
            "boundary_weight": 2.0,  # 边界力权重
            "boundary_buffer": 5.0,  # 边界缓冲区
            "path_radius": 3.0,  # 路径影响半径
            "path_weight": 1.0,  # 路径跟随权重
            "prediction_distance": 10.0,  # 预测距离
            "formation_weight": 1.0,  # 队形保持权重
            "predator_avoid_weight": 3.0,  # 捕食者躲避权重
            "predator_radius": 15.0,  # 捕食者影响半径
            "arrival_slow_radius": 5.0,  # 到达减速半径
            "interaction_weight": 1.0,  # 群体间交互权重
            
            # 学习参数
            "learning_rate": 0.1,  # 学习率
            "exploration_rate": 0.3,  # 探索率
            "memory_capacity": 1000,  # 记忆容量
            
            # 环境感知参数
            "sensor_range": 15.0,  # 传感器范围
            "sensor_accuracy": 0.9,  # 传感器精度
            "obstacle_response_weight": 2.0,  # 障碍物响应权重
            "predator_response_weight": 3.0,  # 捕食者响应权重
            "resource_seek_weight": 0.5,  # 资源寻求权重
            "hazard_avoid_weight": 3.0,  # 危险回避权重
            "time_flow_rate": 0.1,  # 时间流逝速度
            
            # 物理参数
            "gravity_enabled": True,  # 重力开关
            "air_resistance_enabled": True,  # 空气阻力开关
            "buoyancy_enabled": False,  # 浮力开关
            "fluid_level": 0.0,  # 流体水平面高度
            
            # 性能参数
            "update_rate": 60,  # FPS
            "spatial_partitioning": True,  # 空间分区优化
            "neighbor_search_optimization": True,  # 邻居搜索优化
            "parallel_computation": True,  # 并行计算
        }
        
        # 当前配置
        self.settings = self.default_settings.copy()
        
        # 配置验证规则
        self.validation_rules = {
            # 基本Boids参数
            "cohesion_weight": (float, 0.0, 10.0),
            "separation_weight": (float, 0.0, 10.0),
            "alignment_weight": (float, 0.0, 10.0),
            "perception_radius": (float, 0.1, 100.0),
            
            # 移动参数
            "max_speed": (float, 0.1, 50.0),
            "max_acceleration": (float, 0.01, 10.0),
            "max_force": (float, 0.01, 5.0),
            
            # 群体参数
            "member_count": (int, 1, 1000),
            "swarm_type": (str, ["鸟类", "鱼类", "昆虫", "自定义"]),
            
            # 行为开关
            "seek_enabled": (bool, None, None),
            "obstacle_avoidance_enabled": (bool, None, None),
            "wander_enabled": (bool, None, None),
            "boundary_enabled": (bool, None, None),
            "predator_avoid_enabled": (bool, None, None),
            "arrival_enabled": (bool, None, None),
            "formation_enabled": (bool, None, None),
            "path_following_enabled": (bool, None, None),
            "interaction_enabled": (bool, None, None),
            "learning_enabled": (bool, None, None),
            "environment_awareness_enabled": (bool, None, None),
            
            # 高级行为参数
            "personal_space": (float, 0.1, 20.0),
            "obstacle_radius": (float, 0.1, 50.0),
            "seek_weight": (float, 0.0, 10.0),
            "flee_weight": (float, 0.0, 10.0),
            "wander_weight": (float, 0.0, 5.0),
            "wander_radius": (float, 0.1, 50.0),
            "wander_distance": (float, 0.1, 100.0),
            "wander_jitter": (float, 0.0, 5.0),
            "boundary_weight": (float, 0.0, 10.0),
            "boundary_buffer": (float, 0.1, 50.0),
            "path_radius": (float, 0.1, 50.0),
            "path_weight": (float, 0.0, 10.0),
            "prediction_distance": (float, 0.1, 100.0),
            "formation_weight": (float, 0.0, 10.0),
            "predator_avoid_weight": (float, 0.0, 10.0),
            "predator_radius": (float, 1.0, 100.0),
            "arrival_slow_radius": (float, 0.1, 50.0),
            "interaction_weight": (float, 0.0, 5.0),
            
            # 学习参数
            "learning_rate": (float, 0.01, 1.0),
            "exploration_rate": (float, 0.0, 1.0),
            "memory_capacity": (int, 100, 10000),
            
            # 环境感知参数
            "sensor_range": (float, 1.0, 50.0),
            "sensor_accuracy": (float, 0.1, 1.0),
            "obstacle_response_weight": (float, 0.0, 5.0),
            "predator_response_weight": (float, 0.0, 5.0),
            "resource_seek_weight": (float, 0.0, 2.0),
            "hazard_avoid_weight": (float, 0.0, 5.0),
            "time_flow_rate": (float, 0.01, 2.0),
            
            # 物理参数
            "gravity_enabled": (bool, None, None),
            "air_resistance_enabled": (bool, None, None),
            "buoyancy_enabled": (bool, None, None),
            "fluid_level": (float, -100.0, 100.0),
            
            # 性能参数
            "update_rate": (int, 1, 240),
            "spatial_partitioning": (bool, None, None),
            "parallel_computation": (bool, None, None),
            
            # 队形类型
            "formation_type": (str, ["无", "V字形", "直线", "圆形", "楔形", "球形"]),
        }
        
        # 加载配置
        self.load()
        
    def _get_default_config_path(self):
        """
        获取默认配置文件路径
        """
        # 获取插件目录
        plugin_dir = Path(__file__).parent
        return plugin_dir / "config.json"
        
    def get(self, key, default=None):
        """
        获取配置值
        """
        return self.settings.get(key, default)
        
    def set(self, key, value):
        """
        设置配置值
        """
        # 验证配置值
        if self._validate_setting(key, value):
            self.settings[key] = value
            return True
        else:
            print(f"配置值验证失败: {key} = {value}")
            return False
            
    def _validate_setting(self, key, value):
        """
        验证配置值是否有效
        """
        if key not in self.validation_rules:
            return True  # 没有验证规则的配置项直接通过
            
        rule = self.validation_rules[key]
        value_type, min_val, max_val = rule
        
        # 类型检查
        if not isinstance(value, value_type):
            return False
            
        # 范围检查
        if value_type in (int, float) and min_val is not None and max_val is not None:
            if value < min_val or value > max_val:
                return False
                
        # 枚举检查
        if value_type == str and isinstance(min_val, list):
            if value not in min_val:
                return False
                
        return True
        
    def reset_to_default(self):
        """
        重置为默认配置
        """
        self.settings = self.default_settings.copy()
        self.save()
        
    def load_from_dict(self, config_dict):
        """
        从字典加载配置
        """
        for key, value in config_dict.items():
            self.set(key, value)
            
    def to_dict(self):
        """
        导出配置为字典
        """
        return self.settings.copy()
        
    def load(self):
        """
        从文件加载配置
        """
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                    self.load_from_dict(config_data)
                print(f"配置已从 {self.config_file} 加载")
            else:
                print("配置文件不存在，使用默认配置")
        except Exception as e:
            print(f"加载配置文件时出错: {e}")
            print("使用默认配置")
            
    def save(self):
        """
        保存配置到文件
        """
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            # 保存配置
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, ensure_ascii=False, indent=4)
            print(f"配置已保存到 {self.config_file}")
            return True
        except Exception as e:
            print(f"保存配置文件时出错: {e}")
            return False
            
    def get_all_settings(self):
        """
        获取所有配置项
        """
        return self.settings.copy()
        
    def update_setting(self, key, value):
        """
        更新单个配置项并保存
        """
        if self.set(key, value):
            return self.save()
        return False
        
    def export_config(self, file_path):
        """
        导出配置到指定文件
        """
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, ensure_ascii=False, indent=4)
            print(f"配置已导出到 {file_path}")
            return True
        except Exception as e:
            print(f"导出配置时出错: {e}")
            return False
            
    def import_config(self, file_path):
        """
        从指定文件导入配置
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
                self.load_from_dict(config_data)
                self.save()
            print(f"配置已从 {file_path} 导入")
            return True
        except Exception as e:
            print(f"导入配置时出错: {e}")
            return False
            
    def get_setting_info(self, key):
        """
        获取配置项信息
        """
        if key in self.validation_rules:
            rule = self.validation_rules[key]
            return {
                "type": rule[0].__name__,
                "min": rule[1],
                "max": rule[2],
                "default": self.default_settings.get(key)
            }
        return None
        
    def validate_all_settings(self):
        """
        验证所有配置项
        """
        invalid_settings = []
        for key, value in self.settings.items():
            if not self._validate_setting(key, value):
                invalid_settings.append(key)
        return invalid_settings