"""
Bộ Tự Hiệu Chuẩn Phản Xạ Sinh Tồn (Dynamic Reflex Parameter Auto-Tuner)
Tự động điều chỉnh các ngưỡng bơm máu, né lùi (Iframe Dodge) và cự ly thả diều dựa trên dữ liệu tử vong và nguy cấp thực tế.
"""

import json
import logging
import os
from typing import Dict

logger = logging.getLogger("ReflexTuner")


class ReflexParameterTuner:
    """
    Tự động tối ưu hóa tham số phản xạ của Core Engine theo phong cách chơi và độ khó của map.
    """

    def __init__(self, config_path: str = "captures/tuned_reflex_config.json"):
        self.config_path = config_path
        self.flask_hp_threshold: float = 0.55
        self.burst_dodge_threshold: float = 0.22
        self.kiting_distance: float = 35.0
        self.emergency_chicken_hp: float = 0.18

        self.consecutive_deaths: int = 0
        self.near_death_events: int = 0
        self.successful_runs: int = 0
        self._load_config()

    def record_death(self, area_level: int = 0) -> Dict[str, float]:
        self.consecutive_deaths += 1
        self.successful_runs = 0

        self.flask_hp_threshold = min(0.75, self.flask_hp_threshold + 0.05)
        self.burst_dodge_threshold = max(0.15, self.burst_dodge_threshold - 0.02)
        self.kiting_distance = min(50.0, self.kiting_distance + 3.0)
        self.emergency_chicken_hp = min(0.28, self.emergency_chicken_hp + 0.02)

        logger.warning(
            f"[ReflexTuner] Phát hiện tử trận (Chuỗi: {self.consecutive_deaths})! "
            f"Tự động siết an toàn: Flask HP={self.flask_hp_threshold:.2f}, "
            f"Dodge Delta={self.burst_dodge_threshold:.2f}, Kite Dist={self.kiting_distance:.1f}"
        )
        self._save_config()
        return self.get_current_parameters()

    def record_near_death(self) -> None:
        self.near_death_events += 1
        if self.near_death_events >= 3:
            self.flask_hp_threshold = min(0.70, self.flask_hp_threshold + 0.03)
            self.kiting_distance = min(48.0, self.kiting_distance + 2.0)
            self.near_death_events = 0
            self._save_config()

    def record_clean_run(self) -> Dict[str, float]:
        self.successful_runs += 1
        self.consecutive_deaths = 0

        if self.successful_runs >= 5:
            self.flask_hp_threshold = max(0.55, self.flask_hp_threshold - 0.02)
            self.burst_dodge_threshold = min(0.22, self.burst_dodge_threshold + 0.01)
            self.kiting_distance = max(35.0, self.kiting_distance - 1.5)
            self.successful_runs = 0
            self._save_config()

        return self.get_current_parameters()

    def get_current_parameters(self) -> Dict[str, float]:
        return {
            "flask_hp_threshold": round(self.flask_hp_threshold, 2),
            "burst_dodge_threshold": round(self.burst_dodge_threshold, 2),
            "kiting_distance": round(self.kiting_distance, 1),
            "emergency_chicken_hp": round(self.emergency_chicken_hp, 2),
            "consecutive_deaths": self.consecutive_deaths,
        }

    def _save_config(self) -> None:
        os.makedirs(os.path.dirname(self.config_path) or ".", exist_ok=True)
        try:
            with open(self.config_path, "w", encoding="utf-8") as f:
                json.dump(self.get_current_parameters(), f, indent=2)
        except Exception as e:
            logger.error(f"[ReflexTuner] Lỗi lưu cấu hình: {e}")

    def _load_config(self) -> None:
        if os.path.exists(self.config_path):
            try:
                with open(self.config_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    self.flask_hp_threshold = data.get("flask_hp_threshold", 0.55)
                    self.burst_dodge_threshold = data.get("burst_dodge_threshold", 0.22)
                    self.kiting_distance = data.get("kiting_distance", 35.0)
                    self.emergency_chicken_hp = data.get("emergency_chicken_hp", 0.18)
            except Exception as e:
                logger.error(f"[ReflexTuner] Lỗi đọc cấu hình: {e}")
