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


// Constants
const std::string PLUGIN_NAME = "EchoesOfTheEnd";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log";
const std::string gameExecutable = "TheDarken-Win64-Shipping.exe";
const float baseAspect = 1.777778; // Game native aspect ratio

// 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_aspect_ratio_fix_enabled = false;
static bool g_fov_fix_enabled = false;
static bool g_DOF_fix_enabled = false;
static bool g_CA_fix_enabled = false;
static bool g_Vignetting_fix_enabled = false;
static bool g_Fog_fix_enabled = false;
static int g_AdditionalFOVValue = 0;

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

// AOB Scan pointers
static uint8_t* WorldFOVaddress = nullptr;
static uint8_t* FOVaddress = nullptr;
static uint8_t* Aspectaddress = nullptr;
static uint8_t* DOFaddress = nullptr;
static uint8_t* CAaddress = nullptr;
static uint8_t* Vignettingaddress = nullptr;
static uint8_t* Fogaddress = nullptr;

// Hooking
static SafetyHookMid WorldFOVHook{};
static SafetyHookMid FOVHook{};
static SafetyHookMid AspectHook{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);
static void AspectFixEnabled(bool fix_enabled);
static void DOFFixEnabled(bool fix_enabled);
static void CAFixEnabled(bool fix_enabled);
static void VignettingFixEnabled(bool fix_enabled);
static void FogFixEnabled(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 (WorldFOVaddress == nullptr) {
            constexpr auto FOVStringObfuscated = make_obfuscated<0x4A>("77 ?? 48 ?? ?? FF ?? ?? ?? ?? ?? F3 0F ?? ?? ?? 48");
            WorldFOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"TheDarken-Win64-Shipping.exe" + 3C86F14 - 48 8B 01           - mov rax, [rcx]
            //"TheDarken-Win64-Shipping.exe" + 3C86F17 - FF 90 60 07 00 00  - call qword ptr[rax + 00000760]
            //"TheDarken-Win64-Shipping.exe" + 3C86F1D - F3 0F 10 40 30     - movss xmm0, [rax + 30]
            //"TheDarken-Win64-Shipping.exe" + 3C86F22 - 48 83 C4 28        - add rsp, 28
            //"TheDarken-Win64-Shipping.exe" + 3C86F26 - C3                 - ret

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

        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);
            //"TheDarken-Win64-Shipping.exe" + 365E250 - EB 08                   - jmp "TheDarken-Win64-Shipping.exe" + 365E25A
            //"TheDarken-Win64-Shipping.exe" + 365E252 - F3 0F 10 83 30 02 00 00 - movss xmm0, [rbx + 00000230]
            //"TheDarken-Win64-Shipping.exe" + 365E25A - F3 0F 11 47 30          - movss[rdi + 30], xmm0
            //"TheDarken-Win64-Shipping.exe" + 365E25F - 8B 83 54 02 00 00       - mov eax, [rbx + 00000254]
            //"TheDarken-Win64-Shipping.exe" + 365E265 - 89 47 5C                - mov[rdi + 5C], eax
            //"TheDarken-Win64-Shipping.exe" + 365E268 - 0F B6 8B 59 02 00 00    - movzx ecx, byte ptr[rbx + 00000259]
            //"TheDarken-Win64-Shipping.exe" + 365E26F - 33 4F 68                - xor ecx, [rdi + 68]

            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 += 0x0a;
                Aspectaddress = FOVaddress + 0x0b;
                logger->info("Aspect ratio signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(Aspectaddress));
            }
        }

        if (DOFaddress == nullptr) {
            constexpr auto DOFStringObfuscated = make_obfuscated<0x4A>("75 ?? BF 04 ?? ?? ?? 8B ?? ?? 48 ?? ?? E8");
            DOFaddress = Memory::AOBScan(gameExecutable, DOFStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"TheDarken-Win64-Shipping.exe" + 26E89B2 - 75 05          - jne "TheDarken-Win64-Shipping.exe" + 26E89B9
            //"TheDarken-Win64-Shipping.exe" + 26E89B4 - BF 04 00 00 00 - mov edi, "Echoes Of The End._Init_thread_epoch"
            //"TheDarken-Win64-Shipping.exe" + 26E89B9 - 8B 3C 37       - mov edi, [rdi + rsi]
            //"TheDarken-Win64-Shipping.exe" + 26E89BC - 48 8B CB       - mov rcx, rbx
            //"TheDarken-Win64-Shipping.exe" + 26E89BF - E8 DC 91 68 01 - call "TheDarken-Win64-Shipping.exe" + 3D71BA0

            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));
                DOFaddress += 0x7;
            }
        }

        if (CAaddress == nullptr) {
            constexpr auto CAStringObfuscated = make_obfuscated<0x4A>("7F ?? 44 89 ?? ?? ?? ?? ?? 43 ?? ?? ?? 39 05");
            CAaddress = Memory::AOBScan(gameExecutable, CAStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"TheDarken-Win64-Shipping.exe" + 3D6D452 - 48 8B 05 67 F0 32 06 - mov rax, ["TheDarken-Win64-Shipping.exe" + A09C4C0]
            //"TheDarken-Win64-Shipping.exe" + 3D6D459 - 44 39 38             - cmp[rax], r15d
            //"TheDarken-Win64-Shipping.exe" + 3D6D45C - 7F 07                - jg "TheDarken-Win64-Shipping.exe" + 3D6D465
            //"TheDarken-Win64-Shipping.exe" + 3D6D45E - 44 89 BB 1C 20 00 00 - mov[rbx + 0000201C], r15d
            //"TheDarken-Win64-Shipping.exe" + 3D6D465 - 43 8B 04 26          - mov eax, [r14 + r12]

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

        if (Vignettingaddress == nullptr) {
            constexpr auto VignettingStringObfuscated = make_obfuscated<0x4A>("8B ?? 83 ?? ?? 7D ?? 44 89");
            Vignettingaddress = Memory::AOBScan(gameExecutable, VignettingStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"TheDarken-Win64-Shipping.exe" + 3D6D4E6 - 44 89 BB 24 20 00 00 - mov[rbx + 00002024], r15d
            //"TheDarken-Win64-Shipping.exe" + 3D6D4ED - 48 8B 05 3C D9 32 06 - mov rax, ["TheDarken-Win64-Shipping.exe" + A09AE30]
            //"TheDarken-Win64-Shipping.exe" + 3D6D4F4 - 8B 08                - mov ecx, [rax]
            //"TheDarken-Win64-Shipping.exe" + 3D6D4F6 - 83 F9 02             - cmp ecx, 02
            //"TheDarken-Win64-Shipping.exe" + 3D6D4F9 - 7D 09                - jnl "TheDarken-Win64-Shipping.exe" + 3D6D504

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

        if (Fogaddress == nullptr) {
            constexpr auto FogStringObfuscated = make_obfuscated<0x4A>("74 ?? 48 8B ?? ?? ?? ?? ?? 83 ?? ?? ?? 75 ?? 40 ?? ?? EB ?? 40 ?? ?? 48");            
            Fogaddress = Memory::AOBScan(gameExecutable, FogStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"TheDarken-Win64-Shipping.exe" + 22FCE21 - 48 8B 05 F8 9C C7 07 - mov rax, ["TheDarken-Win64-Shipping.exe" + 9F76B20]
            //"TheDarken-Win64-Shipping.exe" + 22FCE28 - 83 78 04 01          - cmp dword ptr[rax + 04], 01
            //"TheDarken-Win64-Shipping.exe" + 22FCE2C - 75 05                - jne "TheDarken-Win64-Shipping.exe" + 22FCE33
            //"TheDarken-Win64-Shipping.exe" + 22FCE2E - 40 B6 01             - mov sil, 01
            //"TheDarken-Win64-Shipping.exe" + 22FCE31 - EB 03                - jmp "TheDarken-Win64-Shipping.exe" + 22FCE36

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

        if (FOVaddress && Aspectaddress && Aspectaddress && DOFaddress && CAaddress && Vignettingaddress && Fogaddress) {
            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 (Aspectaddress) AspectFixEnabled(g_aspect_ratio_fix_enabled);
        if (DOFaddress) DOFFixEnabled(g_DOF_fix_enabled);
        if (CAaddress) CAFixEnabled(g_CA_fix_enabled);
        if (Vignettingaddress) VignettingFixEnabled(g_Vignetting_fix_enabled);
        if (Fogaddress) FogFixEnabled(g_Fog_fix_enabled);
    }
    else {
        if (FOVaddress) FOVFixEnabled(false);
        if (Aspectaddress) AspectFixEnabled(false);
        if (DOFaddress) DOFFixEnabled(false);
        if (CAaddress) CAFixEnabled(false);
        if (Vignettingaddress) VignettingFixEnabled(false);
        if (Fogaddress) FogFixEnabled(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 SetAspectRatioFixEnabled(bool enabled, bool init)
{
    g_aspect_ratio_fix_enabled = enabled;
    if (!init) AspectFixEnabled(g_aspect_ratio_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 SetCAFixEnabled(bool enabled, bool init)
{
    g_CA_fix_enabled = enabled;
    if (!init) CAFixEnabled(g_CA_fix_enabled);
}

extern "C" __declspec(dllexport) void SetVignettingFixEnabled(bool enabled, bool init)
{
    g_Vignetting_fix_enabled = enabled;
    if (!init) VignettingFixEnabled(g_Vignetting_fix_enabled);
}

extern "C" __declspec(dllexport) void SetFogFixEnabled(bool enabled, bool init)
{
    g_Fog_fix_enabled = enabled;
    if (!init) FogFixEnabled(g_Fog_fix_enabled);
}

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

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

extern "C" __declspec(dllexport) float GetCompensatedFOV() {
    return g_Compensated_FOV;
}

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

// Code injection functions
static void FOVFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && WorldFOVaddress) {
        if (!WorldFOVHook) { // Hook only once
            WorldFOVHook = safetyhook::create_mid(WorldFOVaddress,
                [](SafetyHookContext& ctx) {
                    g_FOV_In = ctx.xmm0.f32[0];
                    g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalFOVValue : 0);
                });
        }
        else WorldFOVHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled) {
        if (WorldFOVHook) WorldFOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

static void AspectFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && FOVaddress != nullptr) {
        if (!FOVHook) { // Hook only once
            FOVHook = safetyhook::create_mid(FOVaddress,
                [](SafetyHookContext& ctx) {
                    g_Compensated_FOV = ctx.xmm0.f32[0] = Maths::CompensateHorizontalFOV(ctx.xmm0.f32[0], baseAspect, aspectRatio); // Compensation is required when aspect fix is checked
                                      - (g_fov_fix_enabled ? g_AdditionalFOVValue : 0);
                });
        }
        else FOVHook.enable();
    }
    if (!fix_enabled && FOVHook)
        FOVHook.disable();

    if (g_fix_enabled && fix_enabled && Aspectaddress != nullptr) {
        if (!AspectHook) {
            AspectHook = safetyhook::create_mid(Aspectaddress,
                [](SafetyHookContext& ctx) {
                    ctx.rax = *reinterpret_cast<uint32_t*>(&aspectRatio);
                });
        }
        else AspectHook.enable();
        logger->info("Aspect ratio fix enabled");
    }
    if (!fix_enabled && AspectHook) {
        AspectHook.disable();
        logger->info("Aspect ratio fix disabled");
    }}

// Memory patch fixes
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 CAFixEnabled(bool fix_enabled) {
    if (g_CA_fix_enabled && fix_enabled && CAaddress) {
        Memory::PatchBytes(CAaddress, "\x90\x90", 2); // NOP jg "TheDarken-Win64-Shipping.exe"+3D6D465
        logger->info("Chromatics aberrations fix enabled");
    }
    if (!fix_enabled && CAaddress) {
        Memory::RestoreBytes(CAaddress);
        logger->info("Chromatics aberrations fix disabled");
    }
}

static void VignettingFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && Vignettingaddress) {
        Memory::PatchBytes(Vignettingaddress, "\x31\xC9", 2); // xor ecx,ecx r.Tonemapper.Quality=0
        logger->info("Vignetting fix enabled");
    }
    if (!fix_enabled && Vignettingaddress) {
        Memory::RestoreBytes(Vignettingaddress);
        logger->info("Vignetting fix disabled");
    }
}

static void FogFixEnabled(bool fix_enabled) {
    if (g_fix_enabled && fix_enabled && Fogaddress) {
        Memory::PatchBytes(Fogaddress, "\xEB", 1); // jne "TheDarken-Win64-Shipping.exe"+22FCE33 => jmp r.Fog = 0
        logger->info("Fog fix enabled");
    }
    if (!fix_enabled && Fogaddress) {
        Memory::RestoreBytes(Fogaddress);
        logger->info("Fog fix disabled");
    }
}

static void InitializeLogger()
{
    try
    {
        std::filesystem::path log_path = std::filesystem::absolute(PLUGIN_LOG);
        if (std::filesystem::exists(log_path))
            std::filesystem::remove(log_path);
        logger = std::make_shared<spdlog::logger>("Echoes Of The End", std::make_shared<spdlog::sinks::rotating_file_sink_st>(PLUGIN_LOG, 10 * 1024 * 1024, 1));
        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;
}