#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 = "Metro Exodus";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log"; 
const std::string gameExecutable = "MetroExodus.exe";

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

// 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_cutscenes_fix_enabled = false;
static bool g_aspect_ratio_fix_enabled = false;
static int g_AdditionalFOVValue = 0;
static int g_AdditionalCutscenesFOVValue = 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* CutscenesFOVaddress = nullptr;
static uint8_t* Aspectaddress_1 = nullptr;
static uint8_t* Aspectaddress_2 = nullptr;

// Hooking
static SafetyHookMid FOVHook{};
static SafetyHookMid CutscenesFOVHook{};
static SafetyHookMid AspectRatioHook_1{};
static SafetyHookMid AspectRatioHook_2{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);
static void CutscenesFOVFixEnabled(bool fix_enabled);
static void AspectRatioFixEnabled(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>("3C ?? 0F 86 ?? ?? ?? ?? F3 0F");
            FOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

            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 += 0x10; // Offset for the target opcode
            }
        }
        if (CutscenesFOVaddress == nullptr) {
            constexpr auto CutscenesFOVStringObfuscated = make_obfuscated<0x4A>("F3 0F ?? ?? ?? ?? ?? ?? E9 96 ?? ?? ?? 48 8B");
            CutscenesFOVaddress = Memory::AOBScan(gameExecutable, CutscenesFOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

            if (!CutscenesFOVaddress)
                logger->warn("Cutscenes FOV signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("Cutscenes FOV signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(CutscenesFOVaddress));
                CutscenesFOVaddress += 0x8; // Offset for the target opcode
            }
        }
        if (Aspectaddress_1 == nullptr) {
            constexpr auto AspectRatioStringObfuscated_1 = make_obfuscated<0x4A>("F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? ?? ?? ?? ?? 89 84 ?? ?? ?? ?? ?? 8B");
            Aspectaddress_1 = Memory::AOBScan(gameExecutable, AspectRatioStringObfuscated_1.decrypt(), PAGE_EXECUTE_READ);

            if (!Aspectaddress_1)
                logger->warn("1st aspect ratio signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("1st aspect ratio signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(Aspectaddress_1));
                Aspectaddress_1 += 0x8; // Offset for the target opcode
            }
        }
        if (Aspectaddress_2 == nullptr) {
            constexpr auto AspectRatioStringObfuscated_2 = make_obfuscated<0x4A>("F3 0F ?? ?? ?? ?? ?? ?? 0F ?? ?? 48 8D ?? ?? ?? ?? ?? F3 48 ?? ?? ?? 49 8D");
            Aspectaddress_2 = Memory::AOBScan(gameExecutable, AspectRatioStringObfuscated_2.decrypt(), PAGE_EXECUTE_READ);

            if (!Aspectaddress_2)
                logger->warn("2nd aspect ratio signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("2nd aspect ratio signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(Aspectaddress_2));
                Aspectaddress_2 += 0x8; // Offset for the target opcode
            }
            if (FOVaddress && CutscenesFOVaddress && Aspectaddress_1 && Aspectaddress_2) {
                logger->info("All AOB signatures found. Ready to patch...");
                logger->info("--------------- AOB scan finished ---------------");
                AOBScanDone = true;
            }
        }
    }
    if (g_fix_enabled) {
        if (FOVaddress) FOVFixEnabled(g_fov_fix_enabled);
        if (CutscenesFOVaddress) CutscenesFOVFixEnabled(g_cutscenes_fix_enabled);
        if (Aspectaddress_1 && Aspectaddress_2) AspectRatioFixEnabled(g_aspect_ratio_fix_enabled);
    }
    else {
        if (FOVaddress) FOVFixEnabled(false);
        if (CutscenesFOVaddress) CutscenesFOVFixEnabled(false);
        if (Aspectaddress_1 && Aspectaddress_2) AspectRatioFixEnabled(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 SetCutscenesFOVFixEnabled(bool enabled, bool init)
{
    g_cutscenes_fix_enabled = enabled;
    if (!init) CutscenesFOVFixEnabled(g_cutscenes_fix_enabled);
}

extern "C" __declspec(dllexport) void SetAspectRatioFixEnabled(bool enabled, bool init)
{
    g_aspect_ratio_fix_enabled = enabled;
    if (!init) {
        AspectRatioFixEnabled(g_aspect_ratio_fix_enabled);
    }
}

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

extern "C" __declspec(dllexport) void SetCutscenesFOV(int fov)
{
    g_AdditionalCutscenesFOVValue = 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) {
        if (!FOVHook) { // Hook only once
            FOVHook = safetyhook::create_mid(FOVaddress,
                [](SafetyHookContext& ctx) {
                    g_FOV_In = ctx.xmm2.f32[0];
                    g_FOV_Out = ctx.xmm2.f32[0] += g_AdditionalFOVValue;
                });
        }
        else FOVHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled && FOVHook) {
        FOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

static void CutscenesFOVFixEnabled (bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && CutscenesFOVaddress) {
        if (!CutscenesFOVHook) { // Hook only once
            CutscenesFOVHook = safetyhook::create_mid(CutscenesFOVaddress,
                [](SafetyHookContext& ctx) {
                    g_FOV_In = ctx.xmm2.f32[0];
                    g_FOV_Out = ctx.xmm2.f32[0] += g_AdditionalCutscenesFOVValue;
                });
        }
        else CutscenesFOVHook.enable();
        logger->info("Cutscenes FOV fix enabled");
    }
    if (!fix_enabled && CutscenesFOVHook) {
        CutscenesFOVHook.disable();
        logger->info("Cutscenes FOV fix disabled");
    }
}

static void AspectRatioFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && Aspectaddress_1 && Aspectaddress_2) {
        if (!AspectRatioHook_1) {
            AspectRatioHook_1 = safetyhook::create_mid(Aspectaddress_1,
                [](SafetyHookContext& ctx) {
                    ctx.xmm6.f32[0] = aspectRatio;
                });
        }
        else {
            AspectRatioHook_1.enable();
        }
        if (!AspectRatioHook_2) {
            AspectRatioHook_2 = safetyhook::create_mid(Aspectaddress_2,
                [](SafetyHookContext& ctx) {
                    ctx.xmm2.f32[0] = aspectRatio;
                });
        }
        else {
            AspectRatioHook_2.enable();
        }
        logger->info("Aspect ratio fix enabled");
    }
    if (!fix_enabled) {
        if (AspectRatioHook_1 && Aspectaddress_1)
            AspectRatioHook_1.disable();
        if (AspectRatioHook_2 && Aspectaddress_2)
            AspectRatioHook_2.disable();

        uint8_t* Aspectaddress_3 = Aspectaddress_2 - 0x12;
        int32_t rel_offset = static_cast<int32_t>(Aspectaddress_3[4]) | (static_cast<int32_t>(Aspectaddress_3[5]) << 8) |
                            (static_cast<int32_t>(Aspectaddress_3[6]) << 16) | (static_cast<int32_t>(Aspectaddress_3[7]) << 24);
        // Calculer l'adresse effective (rip + offset), instruction fait 8 octets
        uint8_t* target_addr = Aspectaddress_3 + 8 + rel_offset; // opcode is 8 bytes long
        *reinterpret_cast<float*>(target_addr) = 1.78f; // movss xmm2, [MetroExodus.exe + 164FEBC] patch base + offset

        logger->info("Aspect ratio 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;
}