#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 = "Days Gone";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log"; 
const std::string gameExecutable = "DaysGone.exe";

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

// Screen informations
static int screenWidth = GetSystemMetrics(SM_CXSCREEN);
static int screenHeight = GetSystemMetrics(SM_CYSCREEN);
static float aspectRatio = (float)screenWidth / screenHeight;

// Plugin states
static bool AOBScanDone = false;
static bool g_fix_enabled = false;
static bool g_fov_fix_enabled = false;
static bool g_hud_fix_enabled = false;
static int g_AdditionalFOVValue = 0;
static int g_AdditionalVehicleFOVValue = 0;
static int g_AdditionalOtherFOVValue = 0;
static float g_HUDLeft = 0;
static float g_HUDRight = 0;
static float g_FOVfactor = 0;

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

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

// Hooking
static SafetyHookMid FOVHook{};
static SafetyHookMid FOVFactorHook{};
static SafetyHookMid HUDHook{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);
static void HUDFixEnabled(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>("F3 0F ?? ?? ?? 48 8D ?? ?? E8 ?? ?? ?? ?? 90 48 ?? ?? 48");
            FOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

            //DaysGone.exe + 46CC96 - 48 8B CB          - mov rcx, rbx
            //DaysGone.exe + 46CC99 - FF 90 80 03 00 00 - call qword ptr[rax + 00000380]
            //DaysGone.exe + 46CC9F - F3 0F 11 47 28    - movss[rdi + 28], xmm0
            //DaysGone.exe + 46CCA4 - 48 8D 4D 00       - lea rcx, [rbp + 00]
            //DaysGone.exe + 46CCA8 - E8 B3 8E FA FF    - call DaysGone.exe + 415B60
            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));
            }
        }

        if (FOVfactorAddress == nullptr) {
            constexpr auto FOVFactorStringObfuscated = make_obfuscated<0x4A>("CC 48 8B ?? ?? F3 0F 10 80 ?? ?? ?? ?? F3 0F");
            FOVfactorAddress = Memory::AOBScan(gameExecutable, FOVFactorStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //DaysGone.exe + 4554E0 - 48 8B 41 28               - mov rax, [rcx + 28]
            //DaysGone.exe + 4554E4 - F3 0F 10 80 68 03 00 00   - movss xmm0, [rax + 00000368]
            //DaysGone.exe + 4554EC - F3 0F 59 41 4C            - mulss xmm0, [rcx + 4C]
            //DaysGone.exe + 4554F1 - C3                        - ret
            //DaysGone.exe + 4554F2 - CC                        - int 3
            if (!FOVfactorAddress)
                logger->warn("FOV factor signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("FOV factor signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(FOVfactorAddress));
                FOVfactorAddress += 0xd;
            }
        }

        if (HUDaddress == nullptr) {
            constexpr auto AspectStringObfuscated = make_obfuscated<0x4A>("48 ?? ?? 48 ?? ?? 66 48 ?? ?? ?? FF ?? 48 8B ?? ?? ?? 0F ?? ??");
            HUDaddress = Memory::AOBScan(gameExecutable, AspectStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

            //DaysGone.exe + 1FBA9E3 - 0F 10 00     - movups xmm0, [rax]
            //DaysGone.exe + 1FBA9E6 - 48 8B C7     - mov rax, rdi
            //DaysGone.exe + 1FBA9E9 - 0F 11 07     - movups[rdi], xmm0
            //DaysGone.exe + 1FBA9EC - 48 83 C4 30  - add rsp, 30
            //DaysGone.exe + 1FBA9F0 - 5F           - pop rdi
            if (!HUDaddress)
                logger->warn("HUD signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("HUD signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(HUDaddress));
                HUDaddress += 0x1B; // Offset for the target opcode
            }
            if (FOVaddress && FOVfactorAddress && HUDaddress) {
                logger->info("All AOB signatures found. Ready to patch...");
                logger->info("--------------- AOB scan finished ---------------");
                AOBScanDone = true;
            }
        }
    }
    if (FOVaddress && FOVfactorAddress && HUDaddress) {
        if (g_fix_enabled) {
            FOVFixEnabled(g_fov_fix_enabled);
            HUDFixEnabled(g_hud_fix_enabled);
        }
        else {
            FOVFixEnabled(false);
            HUDFixEnabled(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 SetHUDFixEnabled(bool enabled, bool init)
{
    g_hud_fix_enabled = enabled;
    if (!init) HUDFixEnabled(g_hud_fix_enabled);
}

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

extern "C" __declspec(dllexport) void SetVehicleFOV(int fov)
{
    g_AdditionalVehicleFOVValue = fov;
}

extern "C" __declspec(dllexport) void SetOtherFOV(int fov)
{
    g_AdditionalOtherFOVValue = fov;
}

extern "C" __declspec(dllexport) void SetHUDLeft(int fov)
{
    g_HUDLeft = (float)fov;
}

extern "C" __declspec(dllexport) void SetHUDRight(int fov)
{
    g_HUDRight = (float)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 functions
static void FOVFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && FOVaddress != nullptr && FOVfactorAddress != nullptr) {
        if (!FOVHook) { // Hook only once
            FOVHook = safetyhook::create_mid(FOVaddress,
                [](SafetyHookContext& ctx) {
                    g_FOV_In = ctx.xmm0.f32[0];
                    if (g_baseFOV == 70) // World base FOV
                        g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalFOVValue : 0); // World FOV
                    else if (g_baseFOV == 90) // Vehicle base FOV
                        g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalVehicleFOVValue : 0); // Vehicle FOV
                    else // Other FOV
                        g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalOtherFOVValue : 0); // Other FOV
                });
        }
        else FOVHook.enable();
        if (!FOVFactorHook) {
            FOVFactorHook = safetyhook::create_mid(FOVfactorAddress,
                [](SafetyHookContext& ctx) {
                    g_FOVfactor = ctx.xmm0.f32[0];
                    g_baseFOV = g_FOV_In / g_FOVfactor;
                });
        }
        else FOVFactorHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled && FOVHook) {
        FOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

static void HUDFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && HUDaddress != nullptr) {
        if (!HUDHook) {
            HUDHook = safetyhook::create_mid(HUDaddress,
                [](SafetyHookContext& ctx) {
                    ctx.xmm0.f32[0] = g_HUDLeft / 100;
                    ctx.xmm0.f32[1] = 0.0f;
                    ctx.xmm0.f32[2] = 1 - (g_HUDRight / 100);
                    ctx.xmm0.f32[3] = 1.0f;
                    memcpy(reinterpret_cast<void*>(ctx.rdi), &ctx.xmm0, sizeof(ctx.xmm0)); // Original code movups [rdi],xmm0
                });
        }
        else HUDHook.enable();
        logger->info("HUD fix enabled");
    }
    if (!fix_enabled && HUDHook) {
        HUDHook.disable();
        logger->info("HUD 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;
}