#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 = "FNAF_SOTM";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log"; 
const std::string gameExecutable = "FNAF_SOTM-Win64-Shipping.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 bool g_hor_plus_fix_enabled = false;
static bool g_DOF_fix_enabled = false;
static bool g_FPS_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;
static uint8_t* HORPLUSaddress = nullptr;
static uint8_t* DOFaddress = nullptr;
static uint8_t* FPSaddress = nullptr;

// Hooking
static SafetyHookMid FOVHook{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);
static void HORPlusFixEnabled(bool fix_enabled);
static void DOFFixEnabled(bool fix_enabled);
static void FPSFixEnabled(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 ---------------");
        if (FOVaddress == nullptr) {
            constexpr auto FOVStringObfuscated = make_obfuscated<0x4A>("EB ?? F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? ?? 8B 83 ?? ?? ?? ?? 89");
            FOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"FNAF_SOTM-Win64-Shipping.exe" + 2BC96B0 - EB 08                   - jmp "FNAF_SOTM-Win64-Shipping.exe" + 2BC96BA
            //"FNAF_SOTM-Win64-Shipping.exe" + 2BC96B2 - F3 0F 10 83 F8 01 00 00 - movss xmm0, [rbx + 000001F8]
            //"FNAF_SOTM-Win64-Shipping.exe" + 2BC96BA - F3 0F 11 47 18          - movss[rdi + 18], xmm0
            //"FNAF_SOTM-Win64-Shipping.exe" + 2BC96BF - 8B 83 08 02 00 00       - mov eax, [rbx + 00000208]
            //"FNAF_SOTM-Win64-Shipping.exe" + 2BC96C5 - 89 47 2C                - mov[rdi + 2C], eax

            if (!FOVaddress)
                logger->warn("FOV signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("FOV signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(FOVaddress));
                FOVaddress += 0xa; // Offset for the target opcode
            }
        }
        if (HORPLUSaddress == nullptr) {
            constexpr auto HORPLUSStringObfuscated = make_obfuscated<0x4A>("41 0F ?? ?? ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? 4C ?? ?? 4D ?? ?? E8");
            HORPLUSaddress = Memory::AOBScan(gameExecutable, HORPLUSStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"FNAF_SOTM-Win64-Shipping.exe" + 2E2D3F3 - 0F 11 56 40             - movups[rsi + 40], xmm2
            //"FNAF_SOTM-Win64-Shipping.exe" + 2E2D3F7 - 0F 85 95 00 00 00       - jne "FNAF_SOTM-Win64-Shipping.exe" + 2E2D492
            //"FNAF_SOTM-Win64-Shipping.exe" + 2E2D3FD - 41 0F B6 96 94 00 00 00 - movzx edx,byte ptr [r14+00000094]
            //"FNAF_SOTM-Win64-Shipping.exe" + 2E2D405 - 48 8D 8D D0 00 00 00    - lea rcx, [rbp + FNAF_SOTMCore.dtor_list_head + A0]
            //"FNAF_SOTM-Win64-Shipping.exe" + 2E2D40C - 4C 8B CE                - mov r9, rsi

            if (!HORPLUSaddress)
                logger->warn("HOR+ signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else
                logger->info("HOR+ signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(HORPLUSaddress));
        }
        if (DOFaddress == nullptr) {
            constexpr auto DOFStringObfuscated = make_obfuscated<0x4A>("8B ?? ?? E8 ?? ?? ?? ?? 8B ?? E8 ?? ?? ?? ?? 84 ?? 74 ?? 48");
            DOFaddress = Memory::AOBScan(gameExecutable, DOFStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"FNAF_SOTM-Win64-Shipping.exe" + 1BBE160 - 48 8B 05 D1 73 AF 03 - mov rax, ["FNAF_SOTM-Win64-Shipping.exe" + 56B5538]
            //"FNAF_SOTM-Win64-Shipping.exe" + 1BBE167 - 48 8B CB             - mov rcx, rbx
            //"FNAF_SOTM-Win64-Shipping.exe" + 1BBE16A - 8B 78 04             - mov edi, [rax + 04]
            //"FNAF_SOTM-Win64-Shipping.exe" + 1BBE16D - E8 2E 2C 47 01       - call "FNAF_SOTM-Win64-Shipping.exe" + 3030DA0
            //"FNAF_SOTM-Win64-Shipping.exe" + 1BBE172 - 8B C8                - mov ecx, eax

            if (!DOFaddress)
                logger->warn("DOF signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("DOF signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(DOFaddress));
            }
        }
        if (FPSaddress == nullptr) {
            constexpr auto FPSStringObfuscated = make_obfuscated<0x4A>("F3 0F ?? ?? ?? EB ?? 0F ?? ?? 48 8B ?? ?? ?? 0F");
            FPSaddress = Memory::AOBScan(gameExecutable, FPSStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"FNAF_SOTM-Win64-Shipping.exe" + 314F2E4 - 3B 05 EE B7 45 02 - cmp eax, ["FNAF_SOTM-Win64-Shipping.exe" + 55AAAD8]
            //"FNAF_SOTM-Win64-Shipping.exe" + 314F2EA - 0F 95 C3          - setne bl
            //"FNAF_SOTM-Win64-Shipping.exe" + 314F2ED - F3 0F 10 04 9F    - movss xmm0, [rdi + rbx * 4]
            //"FNAF_SOTM-Win64-Shipping.exe" + 314F2F2 - EB 03             - jmp "FNAF_SOTM-Win64-Shipping.exe" + 314F2F7
            //"FNAF_SOTM-Win64-Shipping.exe" + 314F2F4 - 0F 28 C6          - movaps xmm0, xmm6

            if (!FPSaddress)
                logger->warn("FPS cap signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else
                logger->info("FPS cap signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(FPSaddress));

            if (FOVaddress && HORPLUSaddress && DOFaddress && FPSaddress) {
                logger->info("All AOB signatures found. Ready to patch...");
                AOBScanDone = true;
            }
            logger->info("--------------- AOB scan finished ---------------");
        }
    }
    if (g_fix_enabled) {
        if (FOVaddress) FOVFixEnabled(g_fov_fix_enabled);
        if (HORPLUSaddress) HORPlusFixEnabled(g_hor_plus_fix_enabled);
        if (DOFaddress) DOFFixEnabled(g_DOF_fix_enabled);
        if (FPSaddress) FPSFixEnabled(g_FPS_fix_enabled);
    }
    else {
        if (FOVaddress) FOVFixEnabled(false);
        if (HORPLUSaddress) HORPlusFixEnabled(false);
        if (DOFaddress) DOFFixEnabled(false);
        if (FPSaddress) FPSFixEnabled(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); // FOV fix must be enabled when aspect ratio is too to compensate FOV
}

extern "C" __declspec(dllexport) void SetHORPlusFixEnabled(bool enabled, bool init)
{
    g_hor_plus_fix_enabled = enabled;
    if (!init) HORPlusFixEnabled(g_hor_plus_fix_enabled);
}

extern "C" __declspec(dllexport) void SetDOFFixEnabled(bool enabled, bool init)
{
    g_DOF_fix_enabled = enabled;
    if (!init) DOFFixEnabled(g_DOF_fix_enabled);
}

extern "C" __declspec(dllexport) void SetFPSFixEnabled(bool enabled, bool init)
{
    g_FPS_fix_enabled = enabled;
    if (!init) FPSFixEnabled(g_FPS_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) {
        if (!FOVHook) { // Hook only once
            FOVHook = safetyhook::create_mid(FOVaddress,
                [](SafetyHookContext& ctx) {
                    g_FOV_In = ctx.xmm0.f32[0];
                    g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalValue : 0);
                });
        }
        else FOVHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled) {
        if (FOVHook) FOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

// Memory patch functions
static void HORPlusFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && HORPLUSaddress) {
        Memory::PatchBytes(HORPLUSaddress, "\x31\xD2\x90\x90\x90\x90\x90\x90", 8); // xor edx,edx AspectRatioAxisConstraint=AspectRatio_MaintainYFOV
        logger->info("HOR+ fix enabled");
    }
    if (!fix_enabled && HORPLUSaddress) {
        Memory::RestoreBytes(HORPLUSaddress);
        logger->info("HOR+ fix disabled");
    }
}

static void DOFFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && DOFaddress) {
        Memory::PatchBytes(DOFaddress, "\x31\xFF\x90", 3); // xor edi,edi r.DepthOfFieldQuality = 0
        logger->info("Depth of field fix enabled");
    }
    if (!fix_enabled && DOFaddress) {
        Memory::RestoreBytes(DOFaddress);
        logger->info("Depth of field fix disabled");
    }
}

static void FPSFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && FPSaddress) {
        Memory::PatchBytes(FPSaddress, "\x0F\x57\xC0\x90\x90", 5); // xorps xmm0,xmm0 (0 = unlimited FPS)
        logger->info("FPS cap fix enabled");
    }
    if (!fix_enabled && FPSaddress) {
        Memory::RestoreBytes(FPSaddress);
        logger->info("FPS cap 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;
}