import math
import time
import random
from dataclasses import dataclass
from typing import Tuple, Optional

@dataclass
class AimConfig:
    """瞄准配置类"""
    aim_intensity: float = 99.9
    target: str = "敌人"
    target_part: str = "头部"
    head_lock: bool = True
    lock_strength: float = 99.9
    health_threshold: int = 1
    continuous_activation: bool = True
    damage_activation: bool = True
    console_output: bool = True

class SmoothAimBot:
    """平滑锁头系统"""
    
    def __init__(self, config: AimConfig):
        self.config = config
        self.is_active = False
        self.current_target = None
        self.smooth_factor = 0.1  # 平滑系数
        self.last_aim_position = (0, 0, 0)  # (x, y, z)
        
        if config.console_output:
            print("Py：激活平滑锁头逻辑")
    
    def calculate_head_position(self, enemy_position: Tuple[float, float, float], 
                              enemy_height: float = 1.8) -> Tuple[float, float, float]:
        """计算敌人头部位置"""
        x, y, z = enemy_position
        # 头部位置通常在身体高度的0.9倍处
        head_x = x
        head_y = y + enemy_height * 0.9
        head_z = z
        return (head_x, head_y, head_z)
    
    def smooth_aim(self, current_aim: Tuple[float, float, float], 
                  target: Tuple[float, float, float]) -> Tuple[float, float, float]:
        """平滑瞄准函数"""
        current_x, current_y, current_z = current_aim
        target_x, target_y, target_z = target
        
        # 应用平滑过渡
        new_x = current_x + (target_x - current_x) * self.smooth_factor * (self.config.lock_strength / 100)
        new_y = current_y + (target_y - current_y) * self.smooth_factor * (self.config.lock_strength / 100)
        new_z = current_z + (target_z - current_z) * self.smooth_factor * (self.config.lock_strength / 100)
        
        return (new_x, new_y, new_z)
    
    def acquire_target(self, enemy_list: list) -> Optional[dict]:
        """获取最佳瞄准目标"""
        if not enemy_list:
            return None
        
        # 简单的距离优先选择
        best_target = min(enemy_list, 
                         key=lambda enemy: self.calculate_distance(enemy['position']))
        return best_target
    
    def calculate_distance(self, position: Tuple[float, float, float]) -> float:
        """计算到目标的距离"""
        # 假设玩家位置在原点
        return math.sqrt(sum(p**2 for p in position))
    
    def should_activate(self, player_health: int, took_damage: bool = False) -> bool:
        """判断是否应该激活瞄准"""
        if player_health <= self.config.health_threshold:
            return False
        
        if self.config.continuous_activation and self.is_active:
            return True
            
        if self.config.damage_activation and took_damage:
            return True
            
        return self.config.continuous_activation
    
    def track_enemy_head(self, enemy_data: dict, player_health: int, 
                        took_damage: bool = False) -> Tuple[bool, Tuple[float, float, float]]:
        """追踪敌人头部主函数"""
        
        if not self.should_activate(player_health, took_damage):
            self.is_active = False
            return False, self.last_aim_position
        
        self.is_active = True
        
        # 计算头部位置
        head_position = self.calculate_head_position(enemy_data['position'])
        
        # 应用平滑瞄准
        smoothed_aim = self.smooth_aim(self.last_aim_position, head_position)
        self.last_aim_position = smoothed_aim
        
        # 添加一些随机偏移使其更自然（可选）
        if self.config.aim_intensity < 100:
            randomness = (100 - self.config.aim_intensity) / 1000
            smoothed_aim = (
                smoothed_aim[0] + random.uniform(-randomness, randomness),
                smoothed_aim[1] + random.uniform(-randomness, randomness),
                smoothed_aim[2] + random.uniform(-randomness, randomness)
            )
        
        return True, smoothed_aim
    
    def update_config(self, **kwargs):
        """动态更新配置"""
        for key, value in kwargs.items():
            if hasattr(self.config, key):
                setattr(self.config, key, value)
        
        if self.config.console_output:
            print(f"Py：配置已更新 - 强度:{self.config.aim_intensity}%")

# 使用示例
def main():
    # 创建配置
    config = AimConfig()
    
    # 创建锁头系统实例
    aim_bot = SmoothAimBot(config)
    
    # 模拟敌人
    enemy = {
        'name': '敌人1',
        'position': (10.0, 2.0, 5.0),  # (x, y, z)
        'health': 100
    }
    
    # 模拟游戏循环
    for frame in range(100):
        print(f"\n帧 {frame + 1}:")
        
        # 追踪敌人头部
        is_aiming, aim_position = aim_bot.track_enemy_head(
            enemy, 
            player_health=100,
            took_damage=(frame == 10)  # 第10帧模拟受到伤害
        )
        
        if is_aiming:
            print(f"瞄准中 → 位置: x={aim_position[0]:.2f}, y={aim_position[1]:.2f}, z={aim_position[2]:.2f}")
            
            # 这里可以添加实际的瞄准逻辑
            # 例如：move_mouse_to(aim_position