import math
import json
import time
from dataclasses import dataclass
from typing import Tuple, Dict, Any, List
from enum import Enum

class WeaponType(Enum):
    """武器类型枚举"""
    RIFLE = "rifle"
    SNIPER = "sniper"
    SMG = "smg"
    SHOTGUN = "shotgun"

@dataclass
class AimAssistConfig:
    """瞄准辅助配置"""
    bEnabled: bool = True
    fStrength: float = 999.0
    fRadius: float = 360.0
    fDistance: float = 99.9

@dataclass
class TargetPredictionConfig:
    """目标预测配置"""
    vEnemyPos: Tuple[float, float] = (2080.0, 1080.0)
    vBulletPos: Tuple[float, float] = (2080.0, 1080.0)
    bFollowTarget: bool = True
    fFollowStrength: float = 999.0

@dataclass
class EnhancedFeaturesConfig:
    """增强功能配置"""
    bDynamicPrediction: bool = True
    fPredictionAcc: float = 99.9
    bThermalTracking: bool = True
    fThermalSense: float = 95.0
    bWallPenetration: bool = True
    fPenetrationAcc: float = 85.0

@dataclass
class WeaponSpecificConfig:
    """武器特定配置"""
    fRifleTrack: float = 999.0
    fSniperTrack: float = 999.0
    fSMGTrack: float = 999.0
    fShotgunTrack: float = 999.0

@dataclass
class PerformanceConfig:
    """性能配置"""
    fCPULimit: float = 0.1
    fMemLimit: float = 5.0
    fNetRate: float = 120

class AdvancedAimSystem:
    """高级瞄准系统"""
    
    def __init__(self):
        # 初始化所有配置
        self.aim_assist = AimAssistConfig()
        self.target_prediction = TargetPredictionConfig()
        self.enhanced_features = EnhancedFeaturesConfig()
        self.weapon_specific = WeaponSpecificConfig()
        self.performance = PerformanceConfig()
        
        # 系统状态
        self.is_active = False
        self.current_target = None
        self.current_weapon = WeaponType.RIFLE
        self.aim_history = []
        self.last_prediction = (0, 0)
        
        print("🎯 高级瞄准系统初始化完成")
        self._print_config_summary()
    
    def _print_config_summary(self):
        """打印配置摘要"""
        print(f"🔫 瞄准辅助: {'启用' if self.aim_assist.bEnabled else '禁用'}")
        print(f"🎯 强度: {self.aim_assist.fStrength}")
        print(f"📡 热感追踪: {'启用' if self.enhanced_features.bThermalTracking else '禁用'}")
        print(f"🔍 动态预测: {'启用' if self.enhanced_features.bDynamicPrediction else '禁用'}")
        print(f"💻 性能限制: CPU{self.performance.fCPULimit}% 内存{self.performance.fMemLimit}MB")
    
    def set_weapon(self, weapon_type: WeaponType):
        """设置当前武器"""
        self.current_weapon = weapon_type
        print(f"🔫 切换武器: {weapon_type.value}")
    
    def get_weapon_track_strength(self) -> float:
        """获取当前武器的追踪强度"""
        strength_map = {
            WeaponType.RIFLE: self.weapon_specific.fRifleTrack,
            WeaponType.SNIPER: self.weapon_specific.fSniperTrack,
            WeaponType.SMG: self.weapon_specific.fSMGTrack,
            WeaponType.SHOTGUN: self.weapon_specific.fShotgunTrack
        }
        return strength_map.get(self.current_weapon, 999.0)
    
    def calculate_target_prediction(self, 
                                  enemy_pos: Tuple[float, float],
                                  enemy_velocity: Tuple[float, float] = (0, 0),
                                  bullet_speed: float = 800.0) -> Tuple[float, float]:
        """计算目标预测位置"""
        if not self.enhanced_features.bDynamicPrediction:
            return enemy_pos
        
        # 计算子弹到达时间
        distance = math.sqrt((enemy_pos[0] - self.target_prediction.vBulletPos[0])**2 + 
                           (enemy_pos[1] - self.target_prediction.vBulletPos[1])**2)
        
        if bullet_speed <= 0:
            return enemy_pos
        
        time_to_target = distance / bullet_speed
        
        # 预测目标位置
        pred_x = enemy_pos[0] + enemy_velocity[0] * time_to_target
        pred_y = enemy_pos[1] + enemy_velocity[1] * time_to_target
        
        # 应用预测精度
        accuracy = self.enhanced_features.fPredictionAcc / 100.0
        pred_x = enemy_pos[0] + (pred_x - enemy_pos[0]) * accuracy
        pred_y = enemy_pos[1] + (pred_y - enemy_pos[1]) * accuracy
        
        self.last_prediction = (pred_x, pred_y)
        return (pred_x, pred_y)
    
    def thermal_tracking(self, enemy_pos: Tuple[float, float]) -> bool:
        """热感追踪检测"""
        if not self.enhanced_features.bThermalTracking:
            return True
        
        # 模拟热感检测（简化版）
        thermal_chance = self.enhanced_features.fThermalSense / 100.0
        return random.random() < thermal_chance
    
    def wall_penetration_calc(self, target_pos: Tuple[float, float]) -> float:
        """穿墙精度计算"""
        if not self.enhanced_features.bWallPenetration:
            return 1.0
        
        penetration_acc = self.enhanced_features.fPenetrationAcc / 100.0
        # 这里可以添加更复杂的穿墙逻辑
        return penetration_acc
    
    def smooth_aim(self, 
                  current_aim: Tuple[float, float], 
                  target_pos: Tuple[float, float]) -> Tuple[float, float]:
        """平滑瞄准函数"""
        if not self.aim_assist.bEnabled:
            return target_pos
        
        # 计算距离和方向
        dx = target_pos[0] - current_aim[0]
        dy = target_pos[1] - current_aim[1]
        distance = math.sqrt(dx*dx + dy*dy)
        
        # 检查是否在有效范围内
        if distance > self.aim_assist.fRadius:
            return current_aim
        
        # 应用平滑强度
        strength = min(self.aim_assist.fStrength, 1000.0) / 1000.0
        weapon_strength = self.get_weapon_track_strength() / 1000.0
        combined_strength = strength * weapon_strength
        
        # 平滑移动
        new_x = current_aim[0] + dx * combined_strength
        new_y = current_aim[1] + dy * combined_strength
        
        return (new_x, new_y)
    
    def acquire_target(self, 
                      enemy_list: List[Dict[str, Any]], 
                      player_pos: Tuple[float, float]) -> Dict[str, Any]:
        """获取最佳目标"""
        if not enemy_list:
            return None
        
        best_target = None
        best_score = -1
        
        for enemy in enemy_list:
            enemy_pos = enemy.get('position', (0, 0))
            distance = math.sqrt((enemy_pos[0]-player_pos[0])**2 + 
                               (enemy_pos[1]-player_pos[1])**2)
            
            # 距离检查
            if distance > self.aim_assist.fDistance:
                continue
            
            # 热感追踪检查
            if not self.thermal_tracking(enemy_pos):
                continue
            
            # 计算目标分数（距离越近分数越高）
            score = max(0, self.aim_assist.fDistance - distance)
            
            if score > best_score:
                best_score = score
                best_target = enemy
        
        return best_target
    
    def aim_at_target(self, 
                     enemy_data: Dict[str, Any], 
                     player_pos: Tuple[float, float],
                     current_aim: Tuple[float, float]) -> Dict[str, Any]:
        """主瞄准函数"""
        if not enemy_data or not self.aim_assist.bEnabled:
            return {
                'success': False,
                'aim_position': current_aim,
                'message': '无有效目标或瞄准辅助未启用'
            }
        
        enemy_pos = enemy_data.get('position', (0, 0))
        enemy_velocity = enemy_data.get('velocity', (0, 0))
        bullet_speed = enemy_data.get('bullet_speed', 800.0)
        
        # 目标预测
        predicted_pos = self.calculate_target_prediction(enemy_pos, enemy_velocity, bullet_speed)
        
        # 穿墙精度
        wall_penetration = self.wall_penetration_calc(predicted_pos)
        
        # 平滑瞄准
        final_aim = self.smooth_aim(current_aim, predicted_pos)
        
        # 记录瞄准历史
        self.aim_history.append({
            'timestamp': time.time(),
            'target_pos': enemy_pos,
            'predicted_pos': predicted_pos,
            'final_aim': final_aim,
            'weapon': self.current_weapon.value
        })
        
        # 限制历史记录长度
        if len(self.aim_history) > 100:
            self.aim_history.pop(0)
        
        return {
            'success': True,
            'aim_position': final_aim,
            'predicted_position': predicted_pos,
            'wall_penetration': wall_penetration,
            'weapon_strength': self.get_weapon_track_strength(),
            'thermal_tracking': self.thermal_tracking(enemy_pos)
        }
    
    def get_performance_info(self) -> Dict[str, Any]:
        """获取性能信息"""
        return {
            'cpu_limit': self.performance.fCPULimit,
            'memory_limit': self.performance.fMemLimit,
            'network_rate': self.performance.fNetRate,
            'aim_history_count': len(self.aim_history),
            'current_weapon': self.current_weapon.value,
            'system_active': self.is_active
        }
    
    def save_config(self, filepath: str = "aim_config.json"):
        """保存配置到文件"""
        config_data = {
            'AimAssist': self.aim_assist.__dict__,
            'TargetPrediction': {
                'vEnemyPos': list(self.target_prediction.vEnemyPos),
                'vBulletPos': list(self.target_prediction.vBulletPos),
                'bFollowTarget': self.target_prediction.bFollowTarget,
                'fFollowStrength': self.target_prediction.fFollowStrength
            },
            'EnhancedFeatures': self.enhanced_features.__dict__,
            'WeaponSpecific': self.weapon_specific.__dict__,
            'Performance': self.performance.__dict__
        }
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(config_data, f, indent=2, ensure_ascii=False)
        
        print(f"💾 配置已保存到: {filepath}")
    
    def load_config(self, filepath: str = "aim_config.json"):
        """从文件加载配置"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 更新各个配置
            if 'AimAssist' in config_data:
                for key, value in config_data['AimAssist'].items():
                    if hasattr(self.aim_assist, key):
                        setattr(self.aim_assist, key, value)
            
            # 类似地更新其他配置部分...
            print(f"📂 配置已从 {filepath} 加载")
            
        except FileNotFoundError:
            print("⚠️ 配置文件不存在，使用默认配置")
        except Exception as e:
            print(f"❌ 配置加载错误: {e}")

# 使用示例
def main():
    # 创建瞄准系统实例
    aim_system = AdvancedAimSystem()
    
    # 设置武器
    aim_system.set_weapon(WeaponType.SNIPER)
    
    # 模拟敌人数据
    enemy_data = {
        'name': '敌人1',
        'position': (2100.0, 1100.0),
        'velocity': (5.0, -2.0),  # 移动速度
        'bullet_speed': 1200.0
    }
    
    # 模拟瞄准
    player_pos = (2000.0, 1000.0)
    current_aim = (2050.0, 1050.0)
    
    result = aim_system.aim_at_target(enemy_data, player_pos, current_aim)
    
    print("\n🎯 瞄准结果:")
    print(f"成功: {result['success']}")
    print(f"瞄准位置: {result['aim_position']}")
    print(f"预测位置: {result['predicted_position']}")
    print(f"穿墙精度: {result['wall_penetration']:.1%}")
    print(f"武器强度: {result['weapon_strength']}")
    print(f"热感追踪: {result['thermal_tracking']}")
    
    # 显示性能信息
    perf_info = aim_system.get_performance_info()
    print(f"\n💻 性能信息: {perf_info}")
    
    # 保存配置
    aim_system.save_config("my_aim_config.json")

if __name__ == "__main__":
    main()
