#include "Memory.hpp";
#include "Maths.hpp";
#include "ObfuscateString.h"
#include <string>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <safetyhook.hpp>

// Constants
const std::string PLUGIN_NAME = "Dead Space 2023";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log"; 
const std::string gameExecutable = "Dead Space.exe";

// Logger
std::shared_ptr<spdlog::logger> logger;

// Plugin states
static bool AOBScanDone = false;
static bool g_fix_enabled = false;
static bool g_fov_fix_enabled = false;
static int g_AdditionalValue = 0;

// Shared values
static float g_FOV_In = 0;
static float g_FOV_Out = 0;

// AOB Scan pointers
static uint8_t* FOVaddress = nullptr;

// Hooking
static SafetyHookMid FOVHook{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);

extern "C" __declspec(dllexport) void SetFixEnabled(bool enabled)
{
    g_fix_enabled = enabled;

    if (g_fix_enabled && !AOBScanDone) {
        logger->info("--------------- AOB scan started ---------------");
        constexpr auto FOVStringObfuscated = make_obfuscated<0x4A>("F3 0F ?? ?? ?? ?? ?? ?? 0F 2F ?? ?? ?? ?? ?? 77 ?? 48 8B ?? ?? ?? ?? ?? F3 0F ?? ?? ?? F3 0F ?? ?? ?? ?? ?? ??");
        FOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

        //Dead Space.exe + 1ACB628 - 48 8B 83 10 03 00 00    - mov rax, [rbx + 00000310]
        //Dead Space.exe + 1ACB62F - F3 0F 10 40 6C          - movss xmm0, [rax + 6C]
        //Dead Space.exe + 1ACB634 - F3 0F 59 83 4C 01 00 00 - mulss xmm0, [rbx + 0000014C]
        //Dead Space.exe + 1ACB63C - 48 83 C4 20             - add rsp, 20
        //Dead Space.exe + 1ACB640 - 5B                      - pop rbx
        if (!FOVaddress) {
            logger->warn("FOV signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            logger->info("--------------- AOB scan finished ---------------");
        }
        else {
            logger->info("FOV signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(FOVaddress));
            FOVaddress += 0x1d; // Offset for the target opcode
            AOBScanDone = true;
        }
    }
    if (FOVaddress != nullptr) {
        if (g_fix_enabled) {
            FOVFixEnabled(g_fov_fix_enabled);
        }
        else {
            FOVFixEnabled(false);
            logger->info("All fixes disabled.");
        }
    }
}

// Setters for Reshade addon call
extern "C" __declspec(dllexport) void SetFOVFixEnabled(bool enabled, bool init)
{
    g_fov_fix_enabled = enabled;
    if (!init) FOVFixEnabled(g_fov_fix_enabled); 
}

extern "C" __declspec(dllexport) void SetFOV(int fov)
{
    g_AdditionalValue = fov;
}

// Getters for Reshade addon call
extern "C" __declspec(dllexport) float GetFOVIn() {
    return g_FOV_In;
}

extern "C" __declspec(dllexport) float GetFOVOut() {
    return g_FOV_Out;
}

// Injection function
static void FOVFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && FOVaddress != nullptr) {
        if (!FOVHook) { // Hook only once
            //Memory::PatchBytes(FOVaddress, "\x31\xFF\x90", 3);
            FOVHook = safetyhook::create_mid(FOVaddress,
                [](SafetyHookContext& ctx) {
                    if (ctx.xmm0.f32[0] >= 44.9f) {
                        g_FOV_In = ctx.xmm0.f32[0];
                        g_FOV_Out = ctx.xmm0.f32[0] += g_AdditionalValue;
                    }
                });
        }
        else FOVHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled && FOVHook) {
        FOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

// Initialisation de spdlog avec format personnalisé
static void InitializeLogger()
{
    try
    {
        logger = spdlog::basic_logger_mt("Fixlib", PLUGIN_LOG, true);
        spdlog::set_default_logger(logger);
        // Format : [YYYY-MM-DD HH:MM:SS] [INFO] message
        spdlog::set_pattern("[%Y-%m-%d %H:%M:%S] [%^%l%$] %v");
        spdlog::set_level(spdlog::level::debug);
        logger->flush_on(spdlog::level::debug); // Flush automatically
    }
    catch (const spdlog::spdlog_ex& ex)
    {
        std::string plugin_error_message = "Could not open " + PLUGIN_LOG;
        MessageBoxA(nullptr, plugin_error_message.c_str(), "Logger Error", MB_ICONERROR | MB_OK);
    }
}

// Standard dll entry
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        InitializeLogger();
        logger->info("Plugin {} loaded.", PLUGIN_NAME);
    }
    else if (reason == DLL_PROCESS_DETACH)
    {
        logger->info("Plugin {} unloaded.", PLUGIN_NAME);
        spdlog::drop_all();
    }
    return TRUE;
}