#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 = "SwordOfTheSea";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log";
const std::string gameExecutable = "SwordOfTheSea-Win64-Shipping.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_DOF_fix_enabled = false;
static int g_AdditionalFOVValue = 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* DOFaddress = nullptr;

// Hooking
static SafetyHookMid FOVHook{};

// Prototypes 
static void FOVFixEnabled(bool fix_enabled);
static void DOFFixEnabled(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>("77 ?? 48 ?? ?? FF 90 ?? ?? ?? ?? C5 FA ?? ?? ?? 48");
            FOVaddress = Memory::AOBScan(gameExecutable, FOVStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"SwordOfTheSea-Win64-Shipping.exe" + 38922D9 - FF 90 50 07 00 00 - call qword ptr[rax + 00000750]
            //"SwordOfTheSea-Win64-Shipping.exe" + 38922DF - C5 FA 10 40 30    - vmovss xmm0, [rax + 30]
            //"SwordOfTheSea-Win64-Shipping.exe" + 38922E4 - 48 83 C4 28       - add rsp, 28
            //"SwordOfTheSea-Win64-Shipping.exe" + 38922E8 - C3                - ret
            //"SwordOfTheSea-Win64-Shipping.exe" + 38922E9 - CC                - int 3

            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;
            }
        }

        if (DOFaddress == nullptr) {
            constexpr auto DOFStringObfuscated = make_obfuscated<0x4A>("75 ?? BF ?? ?? ?? ?? 8B ?? ?? 48 ?? ?? E8");
            DOFaddress = Memory::AOBScan(gameExecutable, DOFStringObfuscated.decrypt(), PAGE_EXECUTE_READ);
            //"SwordOfTheSea-Win64-Shipping.exe" + 2359B92 - 75 05          - jne "SwordOfTheSea-Win64-Shipping.exe" + 2359B99
            //"SwordOfTheSea-Win64-Shipping.exe" + 2359B94 - BF 04 00 00 00 - mov edi, "Sword Of The Sea._Init_thread_epoch"
            //"SwordOfTheSea-Win64-Shipping.exe" + 2359B99 - 8B 3C 37       - mov edi, [rdi + rsi]
            //"SwordOfTheSea-Win64-Shipping.exe" + 2359B9C - 48 8B CB       - mov rcx, rbx
            //"SwordOfTheSea-Win64-Shipping.exe" + 2359B9F - E8 EC ED 61 01 - call "SwordOfTheSea-Win64-Shipping.exe" + 3978990

            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 (FOVaddress && DOFaddress ) {
            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 (DOFaddress) DOFFixEnabled(g_DOF_fix_enabled);
    }
    else {
        if (FOVaddress) FOVFixEnabled(false);
        if (DOFaddress) DOFFixEnabled(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 SetDOFFixEnabled(bool enabled, bool init)
{
    g_DOF_fix_enabled = enabled;
    if (!init) DOFFixEnabled(g_DOF_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 GetFOVOut() {
    return g_FOV_Out;
}

// Code 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.xmm0.f32[0];
                    g_FOV_Out = ctx.xmm0.f32[0] += (g_fov_fix_enabled ? g_AdditionalFOVValue : 0);
                });
        }
        else FOVHook.enable();
        logger->info("FOV fix enabled");
    }
    if (!fix_enabled) {
        if (FOVHook) FOVHook.disable();
        logger->info("FOV 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 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>("Sword Of The Sea", 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;
}