#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <bullet/BulletCollision/CollisionDispatch/btCollisionObject.h>
#include <bullet/BulletCollision/CollisionDispatch/btCollisionWorld.h>
#include <bullet/BulletDynamics/ConstraintSolver/btDiscreteDynamicsWorld.h>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/string_cast.hpp>

// 假设Transform是一个包含位置和旋转的类
struct Transform {
    glm::vec3 position;
    glm::quat rotation;

    Transform() : position(0.0f), rotation(1.0f, 0.0f, 0.0f, 0.0f) {}
};

class EnhancedShootingSystem {
public:
    EnhancedShootingSystem(Transform playerCamera, float fieldOfView);

    void update(float deltaTime);
    void shoot();
    void toggleAim();

private:
    void loadConfig(const std::string& filePath);
    void detectTarget();
    void aimAtTarget();
    void decaySpread(float deltaTime);
    void adjustFOV(float deltaTime);

    Transform playerCamera;
    float lockOnRange = 30.0f;
    float lockOnStrength = 0.5f;
    float maxAimAssistAngle = 30.0f;
    float spreadIncrement = 2.0f;
    float maxSpread = 10.0f;
    float spreadDecay = 5.0f;
    float defaultFOV = 60.0f;
    float aimFOV = 50.0f;
    float aimTransitionSpeed = 10.0f;
    int targetLayer = 1 << 9;

    Transform currentTarget;
    float spread = 0.0f;
    bool isAiming = false;
    float currentFOV;
    btCollisionWorld* collisionWorld; // 假设已经初始化
};

EnhancedShootingSystem::EnhancedShootingSystem(Transform playerCamera, float fieldOfView)
    : playerCamera(playerCamera), currentFOV(fieldOfView) {
    loadConfig("Anim.ini");
}

void EnhancedShootingSystem::loadConfig(const std::string& filePath) {
    std::ifstream file(filePath);
    if (!file.is_open()) {
        std::cerr << "Failed to load config file: " << filePath << std::endl;
        return;
    }

    std::unordered_map<std::string, std::string> config;
    std::string line;
    while (std::getline(file, line)) {
        std::istringstream ss(line);
        std::string key, value;
        if (std::getline(ss, key, '=') && std::getline(ss, value)) {
            config[key] = value;
        }
    }

    lockOnRange = std::stof(config["LockOnRange"]);
    lockOnStrength = std::stof(config["LockOnStrength"]);
    maxAimAssistAngle = std::stof(config["MaxAimAssistAngle"]);
    spreadIncrement = std::stof(config["SpreadIncrement"]);
    maxSpread = std::stof(config["MaxSpread"]);
    spreadDecay = std::stof(config["SpreadDecay"]);
    defaultFOV = std::stof(config["DefaultFOV"]);
    aimFOV = std::stof(config["AimFOV"]);
    aimTransitionSpeed = std::stof(config["AimTransitionSpeed"]);
    targetLayer = 1 << std::stoi(config["TargetLayer"]);
}

void EnhancedShootingSystem::update(float deltaTime) {
    detectTarget();
    aimAtTarget();
    decaySpread(deltaTime);
    adjustFOV(deltaTime);
}

void EnhancedShootingSystem::detectTarget() {
    // 假设使用Bullet的射线检测
    btVector3 origin(playerCamera.position.x, playerCamera.position.y, playerCamera.position.z);
    btVector3 direction(glm::dot(playerCamera.rotation, glm::vec3(0.0f, 0.0f, 1.0f)));
    btCollisionObject* hitObject = nullptr; // 假设实现射线检测函数
    // hitObject = PhysicsUtils::raycast(origin, direction, lockOnRange, targetLayer);

    if (hitObject) {
        float angle = glm::degrees(glm::acos(glm::dot(playerCamera.rotation, glm::quat(hitObject->getWorldTransform().getBasis()))));
        if (angle <= maxAimAssistAngle) {
            currentTarget.position = glm::vec3(hitObject->getWorldTransform().getOrigin().x(), hitObject->getWorldTransform().getOrigin().y(), hitObject->getWorldTransform().getOrigin().z());
            currentTarget.rotation = glm::quat(hitObject->getWorldTransform().getRotation());
        }
    } else {
        currentTarget = {};
    }
}

void EnhancedShootingSystem::aimAtTarget() {
    if (currentTarget.position != glm::vec3(0.0f)) {
        glm::vec3 direction = currentTarget.position - playerCamera.position;
        glm::quat targetRotation = glm::rotation(playerCamera.rotation, direction);
        playerCamera.rotation = glm::slerp(playerCamera.rotation, targetRotation, lockOnStrength * deltaTime);
    }
}

void EnhancedShootingSystem::decaySpread(float deltaTime) {
    spread = std::max(spread - spreadDecay * deltaTime, 0.0f);
}

void EnhancedShootingSystem::shoot() {
    if (currentTarget.position != glm::vec3(0.0f)) {
        spread += spreadIncrement;
        spread = std::min(spread, maxSpread);

        // 模拟子弹扩散
        glm::vec3 spreadDirection = glm::normalize(glm::sphericalRand(spread));
        glm::vec3 finalDirection = playerCamera.position + glm::rotate(playerCamera.rotation, spreadDirection);

        // 假设实现射线检测函数
        btCollisionObject* hitObject = nullptr; // PhysicsUtils::raycast(playerCamera.position, finalDirection, lockOnRange);

        if (hitObject) {
            std::cout << "Hit target with spread: " << spread << std::endl;
        } else {
            std::cout << "Missed target with spread: " << spread << std::endl;
        }
    }
}

void EnhancedShootingSystem::adjustFOV(float deltaTime) {
    if (isAiming) {
        currentFOV = glm::lerp(currentFOV, aimFOV, aimTransitionSpeed * deltaTime);
    } else {
        currentFOV = glm::lerp(currentFOV, defaultFOV, aimTransitionSpeed * deltaTime);
    }
}

void EnhancedShootingSystem::toggleAim() {
    isAiming = !isAiming;
}