"""
流体管理器
负责管理流体模拟的整体状态和配置
"""

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

class FluidManager:
    """
    流体管理器
    负责管理流体模拟的整体状态、配置和基本操作
    """
    
    def __init__(self, plugin):
        """
        初始化流体管理器
        
        Args:
            plugin: 水体和流体模拟插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 流体类型定义
        self.fluid_types = {
            'water': {
                'name': '水',
                'description': '标准水体',
                'density': 1000.0,      # kg/m³
                'viscosity': 0.001,     # Pa·s (动力粘度)
                'surface_tension': 0.072,  # N/m
                'compressibility': 4.5e-10,  # 1/Pa
                'color': (0.0, 0.3, 0.8, 0.7),  # RGBA
                'refractive_index': 1.333
            },
            'oil': {
                'name': '油',
                'description': '石油类产品',
                'density': 850.0,
                'viscosity': 0.1,
                'surface_tension': 0.03,
                'compressibility': 1.0e-9,
                'color': (0.2, 0.1, 0.05, 0.8),
                'refractive_index': 1.45
            },
            'honey': {
                'name': '蜂蜜',
                'description': '高粘度流体',
                'density': 1420.0,
                'viscosity': 10.0,
                'surface_tension': 0.06,
                'compressibility': 2.0e-10,
                'color': (0.8, 0.6, 0.1, 0.9),
                'refractive_index': 1.50
            },
            'alcohol': {
                'name': '酒精',
                'description': '低粘度流体',
                'density': 789.0,
                'viscosity': 0.0012,
                'surface_tension': 0.023,
                'compressibility': 1.1e-9,
                'color': (0.8, 0.9, 0.95, 0.6),
                'refractive_index': 1.36
            },
            'lava': {
                'name': '岩浆',
                'description': '高温熔岩',
                'density': 3100.0,
                'viscosity': 1000.0,
                'surface_tension': 0.35,
                'compressibility': 1.0e-11,
                'color': (0.9, 0.3, 0.1, 0.8),
                'refractive_index': 1.8
            }
        }
        
        # 流体模拟配置
        self.simulation_config = {
            'grid_resolution': 64,          # 网格分辨率
            'time_step': 0.016,             # 时间步长(秒)
            'solver_iterations': 10,        # 求解器迭代次数
            'gravity': 9.81,                # 重力加速度(m/s²)
            'boundary_condition': 'closed',  # 边界条件
            'simulation_speed': 1.0         # 模拟速度倍数
        }
        
        # 流体区域
        self.fluid_regions = {}
        self.region_counter = 0
        
        # 流体状态
        self.fluid_states = {
            'total_volume': 0.0,
            'total_mass': 0.0,
            'average_velocity': (0.0, 0.0, 0.0),
            'max_velocity': 0.0,
            'pressure_points': []
        }
        
        # 环境影响因子
        self.environment_factors = {
            'temperature': 20.0,     # 温度(°C)
            'pressure': 101325.0,    # 大气压(Pa)
            'wind_velocity': (0.0, 0.0, 0.0),  # 风速(m/s)
            'gravity_direction': (0.0, -1.0, 0.0)  # 重力方向
        }
        
        # 统计信息
        self.stats = {
            'regions_created': 0,
            'simulation_steps': 0,
            'solver_calls': 0,
            'boundary_collisions': 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.fluid_regions.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['simulation_steps'] += 1
            
        except Exception as e:
            print(f"✗ 流体管理器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_fluid_types(self) -> List[str]:
        """
        获取所有流体类型
        
        Returns:
            流体类型列表
        """
        return list(self.fluid_types.keys())
        
    def get_fluid_info(self, fluid_type: str) -> Optional[Dict[str, Any]]:
        """
        获取流体类型信息
        
        Args:
            fluid_type: 流体类型
            
        Returns:
            流体信息字典或None
        """
        return self.fluid_types.get(fluid_type)
        
    def create_fluid_region(self, fluid_type: str, position: tuple, 
                          size: tuple, initial_velocity: tuple = (0.0, 0.0, 0.0)) -> int:
        """
        创建流体区域
        
        Args:
            fluid_type: 流体类型
            position: 位置坐标 (x, y, z)
            size: 区域大小 (width, height, depth)
            initial_velocity: 初始速度 (vx, vy, vz)
            
        Returns:
            流体区域ID
        """
        try:
            if fluid_type not in self.fluid_types:
                print(f"✗ 无效的流体类型: {fluid_type}")
                return -1
                
            region_id = self.region_counter
            self.region_counter += 1
            
            # 获取流体类型信息
            fluid_info = self.fluid_types[fluid_type]
            
            # 计算体积和质量
            volume = size[0] * size[1] * size[2]
            mass = volume * fluid_info['density']
            
            # 创建区域数据
            region_data = {
                'id': region_id,
                'type': fluid_type,
                'position': position,
                'size': size,
                'volume': volume,
                'mass': mass,
                'velocity': initial_velocity,
                'active': True,
                'creation_time': time.time(),
                'last_update': time.time()
            }
            
            # 存储区域
            self.fluid_regions[region_id] = region_data
            
            # 更新统计数据
            self.stats['regions_created'] += 1
            self.fluid_states['total_volume'] += volume
            self.fluid_states['total_mass'] += mass
            
            print(f"✓ 流体区域已创建: {fluid_info['name']} (ID: {region_id})")
            return region_id
            
        except Exception as e:
            print(f"✗ 流体区域创建失败: {e}")
            import traceback
            traceback.print_exc()
            return -1
            
    def remove_fluid_region(self, region_id: int) -> bool:
        """
        移除流体区域
        
        Args:
            region_id: 流体区域ID
            
        Returns:
            是否移除成功
        """
        try:
            if region_id not in self.fluid_regions:
                print(f"✗ 流体区域不存在: {region_id}")
                return False
                
            region_data = self.fluid_regions[region_id]
            
            # 更新统计数据
            self.fluid_states['total_volume'] -= region_data['volume']
            self.fluid_states['total_mass'] -= region_data['mass']
            
            # 移除区域
            del self.fluid_regions[region_id]
            
            print(f"✓ 流体区域已移除: ID {region_id}")
            return True
            
        except Exception as e:
            print(f"✗ 流体区域移除失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def get_fluid_region(self, region_id: int) -> Optional[Dict[str, Any]]:
        """
        获取流体区域信息
        
        Args:
            region_id: 流体区域ID
            
        Returns:
            流体区域信息或None
        """
        return self.fluid_regions.get(region_id)
        
    def get_all_fluid_regions(self) -> Dict[int, Dict[str, Any]]:
        """
        获取所有流体区域
        
        Returns:
            所有流体区域字典
        """
        return self.fluid_regions.copy()
        
    def update_fluid_region_velocity(self, region_id: int, velocity: tuple):
        """
        更新流体区域速度
        
        Args:
            region_id: 流体区域ID
            velocity: 速度向量 (vx, vy, vz)
        """
        try:
            if region_id not in self.fluid_regions:
                return
                
            self.fluid_regions[region_id]['velocity'] = velocity
            self.fluid_regions[region_id]['last_update'] = time.time()
            
        except Exception as e:
            print(f"✗ 流体区域速度更新失败: {e}")
            
    def update_environment_factors(self, factors: Dict[str, Any]):
        """
        更新环境因子
        
        Args:
            factors: 环境因子字典
        """
        self.environment_factors.update(factors)
        print(f"✓ 环境因子已更新: {factors}")
        
    def get_environment_factors(self) -> Dict[str, Any]:
        """
        获取环境因子
        
        Returns:
            环境因子字典
        """
        return self.environment_factors.copy()
        
    def set_simulation_config(self, config: Dict[str, Any]):
        """
        设置模拟配置
        
        Args:
            config: 配置字典
        """
        self.simulation_config.update(config)
        print(f"✓ 模拟配置已更新: {self.simulation_config}")
        
    def get_simulation_config(self) -> Dict[str, Any]:
        """
        获取模拟配置
        
        Returns:
            模拟配置字典
        """
        return self.simulation_config.copy()
        
    def get_fluid_states(self) -> Dict[str, Any]:
        """
        获取流体状态
        
        Returns:
            流体状态字典
        """
        return self.fluid_states.copy()
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'regions_created': 0,
            'simulation_steps': 0,
            'solver_calls': 0,
            'boundary_collisions': 0
        }
        print("✓ 流体管理器统计信息已重置")
        
    def calculate_reynolds_number(self, fluid_type: str, velocity: float, 
                                characteristic_length: float) -> float:
        """
        计算雷诺数
        
        Args:
            fluid_type: 流体类型
            velocity: 流速
            characteristic_length: 特征长度
            
        Returns:
            雷诺数
        """
        try:
            if fluid_type not in self.fluid_types:
                return 0.0
                
            fluid_info = self.fluid_types[fluid_type]
            density = fluid_info['density']
            viscosity = fluid_info['viscosity']
            
            # 雷诺数 = (密度 × 速度 × 特征长度) / 动力粘度
            reynolds = (density * velocity * characteristic_length) / viscosity
            return reynolds
            
        except Exception as e:
            print(f"✗ 雷诺数计算失败: {e}")
            return 0.0
            
    def calculate_flow_regime(self, reynolds_number: float) -> str:
        """
        根据雷诺数判断流动状态
        
        Args:
            reynolds_number: 雷诺数
            
        Returns:
            流动状态 ('laminar', 'transitional', 'turbulent')
        """
        try:
            if reynolds_number < 2000:
                return 'laminar'  # 层流
            elif reynolds_number < 4000:
                return 'transitional'  # 过渡流
            else:
                return 'turbulent'  # 湍流
                
        except Exception as e:
            print(f"✗ 流动状态判断失败: {e}")
            return 'unknown'