#pragma once

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef NOMINMAX
#define NOMINMAX
#endif

#include <windows.h>
#include <cstdint>
#include <cstddef>
#include <cmath>
#include <algorithm>

#include "common/fixed_keys.hpp"
#include "input/kmbox_net.hpp"
#include "input/human_curve.hpp"
#include "input/quintic_bezier_controller.hpp"

namespace input {

/**
 * @brief Chế độ sinh quỹ đạo chuột mô phỏng sinh học.
 */
enum class MouseTrajectoryMode : uint8_t {
    CubicBezierClassic = 0,    // Bézier bậc 3 truyền thống (HumanCurveGenerator)
    QuinticBezierStealth = 1   // Bézier bậc 5 cao cấp (QuinticBezierController: Minimum Jerk + 11.5Hz Perlin tremor + Gaussian jitter)
};

/**
 * @brief Hồ sơ động học quỹ đạo (Kinematic Profile) để đánh giá độ mượt và gia tốc giật (Jerk Analysis).
 * POD 32 bytes, Zero Dynamic Allocation.
 */
struct KinematicProfile {
    float maxVelocity = 0.0f;       // Vận tốc đỉnh (pixels/giây)
    float maxAcceleration = 0.0f;   // Gia tốc đỉnh (pixels/giây^2)
    float maxJerk = 0.0f;           // Độ giật đỉnh (pixels/giây^3)
    float totalJerkCost = 0.0f;     // Tích phân năng lượng giật: sum(||J||^2 * dt)
    float startAcceleration = 0.0f; // Gia tốc tại điểm bắt đầu (pixels/giây^2)
    float endAcceleration = 0.0f;   // Gia tốc tại điểm kết thúc (pixels/giây^2)
    bool isJerkBounded = true;      // Gia tốc giật nằm trong ngưỡng sinh học an toàn
};

/**
 * @brief Cấu hình bộ điều phối chuột sinh học (Humanized Input Configuration).
 */
struct HumanizedInputConfig {
    MouseTrajectoryMode defaultMode = MouseTrajectoryMode::QuinticBezierStealth;
    float maxAcceptableJerk = 2.5e7f; // Ngưỡng gia tốc giật tối đa cho phép (pixels/s^3)
    float defaultStepDurationSec = 0.008333f; // Nhịp tick 120Hz (~8.33ms)
};

/**
 * @brief HumanizedInputArbiter
 * Bộ điều phối thống nhất cho chuột sinh học và nhấp chuột người thật (Tier 1 Hot Path 120Hz).
 * 
 * Khả năng cốt lõi:
 * 1. Chuyển đổi linh hoạt giữa Bézier bậc 3 (Classic) và Bézier bậc 5 (Commercial Stealth Mode).
 * 2. Hook tích hợp điều khiển chuột mượt qua KMBoxNet với khóa an toàn cửa sổ game tuyệt đối (INV-FOCUS-INTERLOCK-HARDWARE-SAFETY).
 * 3. Phân tích động học vi phân (Kinematic Analysis) xác nhận quỹ đạo mượt mà, triệt tiêu gia tốc giật.
 * 4. 100% Zero Dynamic Allocation, Data-Oriented Design.
 */
class HumanizedInputArbiter {
public:
    explicit HumanizedInputArbiter(const HumanizedInputConfig& config = HumanizedInputConfig{});

    void SetConfig(const HumanizedInputConfig& config) { m_config = config; m_mode = config.defaultMode; }
    const HumanizedInputConfig& Config() const { return m_config; }

    void SetMode(MouseTrajectoryMode mode) { m_mode = mode; }
    MouseTrajectoryMode Mode() const { return m_mode; }

    QuinticBezierController& QuinticController() { return m_quinticCtrl; }
    const QuinticBezierController& QuinticController() const { return m_quinticCtrl; }

    HumanCurveGenerator& CubicGenerator() { return m_cubicGen; }
    const HumanCurveGenerator& CubicGenerator() const { return m_cubicGen; }

    /**
     * @brief Sinh quỹ đạo chuột sinh học vào buffer tĩnh theo chế độ đã chọn (Zero Heap Allocation).
     */
    void GenerateTrajectory(
        Vector2D start,
        Vector2D target,
        common::TrajectoryBuffer& outBuf,
        int steps = 0
    );

    /**
     * @brief Di chuyển chuột mượt mô phỏng sinh học tới tọa độ đích.
     * Khóa an toàn: Tuân thủ 100% INV-FOCUS-INTERLOCK-HARDWARE-SAFETY qua kmbox.IsGameWindowFocused().
     */
    bool MoveMouseSmooth(
        KMBoxNet& kmbox,
        int targetX,
        int targetY,
        int steps = 0,
        int stepDelayMs = 1
    );

    /**
     * @brief Nhấp chuột mô phỏng sinh học với Gaussian dwell time.
     */
    bool ClickMouseHumanized(
        KMBoxNet& kmbox,
        int button,
        float meanMs = 65.0f,
        float stdDevMs = 12.0f
    );

    /**
     * @brief Sinh dwell time theo phân phối sinh học Gauss.
     */
    int GenerateDwellTimeMs(float meanMs = 65.0f, float stdDevMs = 12.0f);

    /**
     * @brief Phân tích động học quỹ đạo vi phân (Kinematic Analysis) để kiểm chứng Jerk.
     */
    static KinematicProfile AnalyzeTrajectory(
        const common::TrajectoryBuffer& traj,
        float stepDurationSec = 0.008333f
    );

private:
    HumanizedInputConfig m_config;
    MouseTrajectoryMode m_mode = MouseTrajectoryMode::QuinticBezierStealth;
    HumanCurveGenerator m_cubicGen;
    QuinticBezierController m_quinticCtrl;
};

} // namespace input
