#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 = "South Of Midnight";
const std::string PLUGIN_LOG = PLUGIN_NAME + ".log"; 
const std::string gameExecutable = "SouthOfMidnight.exe";
const float baseAspect = 1.777778;

// 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_aspect_ratio_fix_enabled = false;
static int g_AdditionalValue = 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* FOVaddress = nullptr;
static uint8_t* Aspectaddress = nullptr;

// Hooking
static SafetyHookMid FOVHook{};
static SafetyHookMid AspectRatioHook{};

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

            //SouthOfMidnight.exe + 357E051 - E8 5A 4A ED FD - call SouthOfMidnight.exe + 1452AB0
            //SouthOfMidnight.exe + 357E056 - 90 - nop
            //SouthOfMidnight.exe + 357E057 - 0F 28 C6 - movaps xmm0, xmm6
            //SouthOfMidnight.exe + 357E05A - 48 8B 8C 24 50 09 00 00 - mov rcx, [rsp + 00000950] <== Injection point
            //SouthOfMidnight.exe + 357E062 - 48 33 CC - xor rcx, rsp
            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 += 4; // Offset for the target opcode
            }
        }
        if (Aspectaddress == nullptr) {
            constexpr auto AspectStringObfuscated = make_obfuscated<0x4A>("EB ?? F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? ?? 8B 87 ?? ?? ?? ?? 89 ?? ?? 0F B6");
            Aspectaddress = Memory::AOBScan(gameExecutable, AspectStringObfuscated.decrypt(), PAGE_EXECUTE_READ);

            //SouthOfMidnight.exe + 3161AB4 - F3 0F 10 87 F8 01 00 00 - movss xmm0, [rdi + 000001F8]
            //SouthOfMidnight.exe + 3161ABC - F3 0F 11 46 18 - movss[rsi + 18], xmm0
            //SouthOfMidnight.exe + 3161AC1 - 8B 87 08 02 00 00 - mov eax, [rdi + 00000208]
            //SouthOfMidnight.exe + 3161AC7 - 89 46 2C - mov[rsi + 2C], eax <== Injection point
            //SouthOfMidnight.exe + 3161ACA - 0F B6 8F 0C 02 00 00 - movzx ecx, byte ptr[rdi + 0000020C]
            if (!Aspectaddress)
                logger->warn("Aspect ratio signature not found. Maybe your game has been updated and is no more compatible with this plugin.");
            else {
                logger->info("Aspect ratio signature found at address: 0x{:X}.", reinterpret_cast<uintptr_t>(Aspectaddress));
                Aspectaddress += 0x15; // Offset for the target opcode
            }
            if (FOVaddress != nullptr && Aspectaddress != nullptr) {
                logger->info("All AOB signatures found. Ready to patch...");
                logger->info("--------------- AOB scan finished ---------------");
                AOBScanDone = true;
            }
        }
    }
    if (FOVaddress && Aspectaddress) {
        if (g_fix_enabled) {
            AspectRatioFixEnabled(g_aspect_ratio_fix_enabled);
            FOVFixEnabled(g_fov_fix_enabled || g_aspect_ratio_fix_enabled);
        }
        else {
            AspectRatioFixEnabled(false);
            FOVFixEnabled(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;
    FOVFixEnabled(g_fov_fix_enabled || g_aspect_ratio_fix_enabled); // FOV fix must be enabled when aspect ratio is too to compensate FOV
}

extern "C" __declspec(dllexport) void SetAspectRatioFixEnabled(bool enabled, bool init)
{
    g_aspect_ratio_fix_enabled = enabled;
    AspectRatioFixEnabled(g_aspect_ratio_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 GetCompensatedFOV() {
    return g_Compensated_FOV;
}

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.xmm0.f32[0];
                    if (g_aspect_ratio_fix_enabled)
                        g_Compensated_FOV = ctx.xmm0.f32[0] = Maths::CompensateHorizontalFOV(g_FOV_In, baseAspect, aspectRatio);
                    else
                        g_Compensated_FOV = 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 && FOVHook) {
        FOVHook.disable();
        logger->info("FOV fix disabled");
    }
}

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

// Initialisation de spdlog avec format personnalisé
static void InitializeLogger()
{
    try
    {
        logger = spdlog::basic_logger_mt("Fixlib", PLUGIN_LOG, true);
        PLUGIN_LOG.c_str();
        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;
}