#pragma once

// ==========================================================
// logger.hpp - Thread-Safe Structured Core Engine Logger
// C++23 Core Engine - AutoPOE2 (DOC-49 & Rule 16)
// ==========================================================

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <fstream>
#include <string>
#include <string_view>
#include <mutex>
#include "overlay.hpp"

namespace common {

inline std::wstring LogDir() {
    wchar_t exePath[MAX_PATH] = {};
    GetModuleFileNameW(nullptr, exePath, MAX_PATH);
    std::wstring dir(exePath);
    const auto slash = dir.find_last_of(L"\\/");
    return (slash == std::wstring::npos) ? L"." : dir.substr(0, slash);
}

/**
 * @brief Singleton quản lý file log trung tâm, đảm bảo thread-safe và giữ handle mở.
 * 
 * Khắc phục hiện tượng suy giảm hiệu năng do mở/đóng tệp liên tục mỗi chu kỳ 120Hz.
 */
class CoreLogger {
private:
    std::mutex m_mutex;
    std::ofstream m_file;
    bool m_initialized = false;

    void EnsureOpen() {
        if (!m_initialized) {
            std::wstring path = LogDir() + L"\\core_log.txt";
            m_file.open(path, std::ios::app);
            m_initialized = true;
        }
    }

public:
    static CoreLogger& Instance() {
        static CoreLogger s_instance;
        return s_instance;
    }

    void Reset() {
        std::lock_guard<std::mutex> lock(m_mutex);
        if (m_file.is_open()) {
            m_file.close();
        }
        std::wstring path = LogDir() + L"\\core_log.txt";
        m_file.open(path, std::ios::trunc);
        m_initialized = true;
    }

    void Log(std::string_view msg, const char* level = nullptr) {
        std::string formatted;
        if (level && level[0] != '\0') {
            formatted = "[" + std::string(level) + "] " + std::string(msg);
        } else {
            formatted = std::string(msg);
        }

        {
            std::lock_guard<std::mutex> lock(m_mutex);
            EnsureOpen();
            if (m_file.is_open()) {
                m_file << formatted << "\n";
                m_file.flush();
            }
        }
        overlay::AddLog(formatted);
    }
};

} // namespace common

inline std::wstring LogDir() {
    return common::LogDir();
}

/**
 * @brief Xóa trắng tệp core_log.txt khi khởi động phiên làm việc mới.
 */
inline void ResetCoreLog() {
    common::CoreLogger::Instance().Reset();
}

/**
 * @brief Ghi thông điệp vào core_log.txt và hiển thị lên Game HUD Overlay.
 * 
 * @param s Chuỗi thông điệp.
 */
inline void CoreLog(const std::string& s) {
    common::CoreLogger::Instance().Log(s, nullptr);
}

/**
 * @brief Ghi nhật ký cấp độ INFO vào core_log.txt.
 */
inline void CoreLogINFO(std::string_view s) {
    common::CoreLogger::Instance().Log(s, "INFO");
}

/**
 * @brief Ghi nhật ký cấp độ WARN vào core_log.txt.
 */
inline void CoreLogWARN(std::string_view s) {
    common::CoreLogger::Instance().Log(s, "WARN");
}

/**
 * @brief Ghi nhật ký cấp độ ERROR vào core_log.txt.
 */
inline void CoreLogERROR(std::string_view s) {
    common::CoreLogger::Instance().Log(s, "ERROR");
}