import math
import numpy as np
from enum import Enum
from collections import deque

class AimAssistMode(Enum):
    PRECISE = 0      # 高精度模式 (狙击类武器)
    BALANCED = 1     # 平衡模式 (步枪类武器)
    AGGRESSIVE = 2   # 激进模式 (冲锋枪/霰弹枪)
    TRACKING = 3     # 追踪模式 (对移动目标优化)
    MAXIMUM = 4      # 最大化辅助模式 (最强效果)

class SuperAimAssist:
    def __init__(self):
        # 核心参数 - 初始化为最大值
        self.base_strength = 1.0           # 基础辅助强度设为最大
        self.max_angle = 60.0              # 最大辅助角度设为最大
        self.smooth_factor = 0.1           # 最小平滑系数 (响应最快)
        
        # 高级功能参数 - 全部启用
        self.target_prediction = True      # 启用目标预测
        self.dynamic_sensitivity = True    # 启用动态灵敏度
        self.adaptive_lock = True         # 启用自适应锁定
        self.recoil_compensation = True    # 启用后坐力补偿
        self.auto_trigger = True          # 启用自动射击触发
        
        # 内部状态
        self.current_mode = AimAssistMode.MAXIMUM
        self.target_history = deque(maxlen=20)  # 增加历史记录长度
        self.last_aim = (0, 0)
        self.lock_strength = 1.0          # 初始锁定强度设为最大
        self.recoil_pattern = []
        self.shots_fired = 0
        self.time_since_last_shot = 0
        
        # 初始化后坐力模式 (更激进的后坐力补偿)
        self._init_recoil_pattern()
    
    def _init_recoil_pattern(self):
        """初始化武器后坐力模式 - 更强的补偿"""
        self.recoil_pattern = []
        for i in range(30):  # 更长的后坐力模式
            self.recoil_pattern.append((
                math.sin(i * 0.25) * 0.8,  # 更强的水平补偿
                i * 0.03                   # 更强的垂直补偿
            ))
    
    def set_mode(self, mode: AimAssistMode):
        """设置辅助瞄准模式 - 添加MAXIMUM模式"""
        self.current_mode = mode
        
        if mode == AimAssistMode.MAXIMUM:
            self.base_strength = 1.0      # 最大辅助强度
            self.max_angle = 60.0         # 最大辅助角度
            self.smooth_factor = 0.1      # 最快响应
            self.target_prediction = True
            self.dynamic_sensitivity = True
            self.adaptive_lock = True
            self.recoil_compensation = True
            self.auto_trigger = True
        elif mode == AimAssistMode.PRECISE:
            self.base_strength = 0.7      # 比原来更强
            self.max_angle = 25.0        # 比原来更宽
            self.smooth_factor = 0.15     # 更快响应
        elif mode == AimAssistMode.BALANCED:
            self.base_strength = 0.85     # 比原来更强
            self.max_angle = 35.0         # 比原来更宽
            self.smooth_factor = 0.2      # 更快响应
        elif mode == AimAssistMode.AGGRESSIVE:
            self.base_strength = 1.0      # 最大强度
            self.max_angle = 45.0         # 很宽的角度
            self.smooth_factor = 0.3     # 适度平滑
        elif mode == AimAssistMode.TRACKING:
            self.base_strength = 0.8      # 较强强度
            self.max_angle = 50.0        # 很宽的角度
            self.smooth_factor = 0.25     # 较快响应
    
    def update_target(self, target_pos, target_vel, delta_time):
        """更新目标信息 - 更快的锁定速度"""
        self.target_history.append((target_pos, target_vel))
        
        # 更快的锁定速度
        if len(self.target_history) > 2:  # 更少的帧数要求
            self.lock_strength = min(1.0, self.lock_strength + delta_time * 2.0)  # 2倍锁定速度
        else:
            self.lock_strength = max(0.0, self.lock_strength - delta_time * 0.5)  # 更慢的衰减
    
    def predict_target_position(self, bullet_speed):
        """预测目标位置 - 更激进的预测"""
        if not self.target_history:
            return None
            
        # 使用更多历史数据进行更准确的预测
        last_pos, last_vel = self.target_history[-1]
        
        # 计算子弹到达时间 (考虑更远的距离)
        distance = np.linalg.norm(np.array(last_pos) - np.array(self.last_aim))
        time_to_target = distance / bullet_speed if bullet_speed > 0 else 0
        
        # 更激进的预测 - 加入加速度估计
        if len(self.target_history) > 3:
            prev_pos, prev_vel = self.target_history[-3]
            accel = (np.array(last_vel) - np.array(prev_vel)) / (2 * 0.1)  # 估算加速度
            time_to_target_sq = time_to_target * time_to_target
            predicted_pos = (
                last_pos[0] + last_vel[0] * time_to_target + 0.5 * accel[0] * time_to_target_sq,
                last_pos[1] + last_vel[1] * time_to_target + 0.5 * accel[1] * time_to_target_sq,
                last_pos[2] + last_vel[2] * time_to_target + 0.5 * accel[2] * time_to_target_sq
            )
        else:
            predicted_pos = (
                last_pos[0] + last_vel[0] * time_to_target * 1.2,  # 增加预测系数
                last_pos[1] + last_vel[1] * time_to_target * 1.2,
                last_pos[2] + last_vel[2] * time_to_target * 1.2
            )
        
        return predicted_pos
    
    def should_auto_fire(self, player_pos, target_pos, current_aim, max_angle=5.0):
        """自动射击判断 - 当准星足够接近目标时自动射击"""
        if not self.auto_trigger:
            return False
            
        # 计算目标方向
        dx = target_pos[0] - player_pos[0]
        dy = target_pos[1] - player_pos[1]
        dz = target_pos[2] - player_pos[2]
        
        target_yaw = math.degrees(math.atan2(dz, dx))
        target_pitch = math.degrees(math.atan2(dy, math.sqrt(dx*dx + dz*dz)))
        
        # 计算角度差异
        yaw_diff = (target_yaw - current_aim[0] + 180) % 360 - 180
        pitch_diff = (target_pitch - current_aim[1] + 180) % 360 - 180
        
        # 检查是否在自动射击范围内
        return abs(yaw_diff) <= max_angle and abs(pitch_diff) <= max_angle
    
    def calculate_aim_assist(self, player_pos, target_pos, current_aim, 
                           bullet_speed=100.0, shots_fired=0, delta_time=0.1):
        """
        最大化效果的辅助瞄准计算
        """
        # 1. 使用更精确的目标预测
        predicted_pos = self.predict_target_position(bullet_speed) if self.target_prediction else target_pos
        if predicted_pos is None:
            return current_aim
            
        # 2. 计算目标方向
        dx = predicted_pos[0] - player_pos[0]
        dy = predicted_pos[1] - player_pos[1]
        dz = predicted_pos[2] - player_pos[2]
        
        target_yaw = math.degrees(math.atan2(dz, dx))
        target_pitch = math.degrees(math.atan2(dy, math.sqrt(dx*dx + dz*dz)))
        
        # 3. 计算角度差异
        yaw_diff = (target_yaw - current_aim[0] + 180) % 360 - 180
        pitch_diff = (target_pitch - current_aim[1] + 180) % 360 - 180
        
        # 4. 更宽松的辅助范围检查
        effective_max_angle = self.max_angle * (1.2 if self.current_mode == AimAssistMode.MAXIMUM else 1.0)
        if abs(yaw_diff) > effective_max_angle or abs(pitch_diff) > effective_max_angle:
            return current_aim  # 超出范围，不辅助
        
        # 5. 计算基础辅助 - 更强的锁定效果
        strength = self.base_strength * (1.0 + 0.8 * self.lock_strength)  # 更强的锁定强度加成
        
        # 6. 根据模式调整 - 最大化模式使用最强设置
        if self.current_mode == AimAssistMode.MAXIMUM:
            yaw_strength = strength * 1.5  # 极强的水平辅助
            pitch_strength = strength * 1.3  # 极强的垂直辅助
        elif self.current_mode == AimAssistMode.TRACKING:
            yaw_strength = strength * 1.5  # 追踪模式更强的水平辅助
            pitc