#include "core/resources/resource_helper.h"

#include <algorithm>
#include <cstddef>
#include <fstream>
#include <iostream>

#include "core/resources/resource_loader.h"

namespace ResourceHelper {
    static bool resource_system_initialized = false;

    bool initializeResourceSystem(const std::string& pack_file, bool enable_fallback) {
        auto& loader = ResourceLoader::getInstance();
        bool ok = loader.initialize(pack_file, enable_fallback);
        resource_system_initialized = ok;

        if (ok && loader.getLoadedResourceCount() > 0) {
            std::cout << "Resource system initialized with pack: " << pack_file << '\n';
        } else if (ok) {
            std::cout << "Resource system using fallback mode (filesystem only)" << '\n';
        }

        return ok;
    }

    void shutdownResourceSystem() {
        if (resource_system_initialized) {
            ResourceLoader::getInstance().shutdown();
            resource_system_initialized = false;
        }
    }

    std::vector<uint8_t> loadFile(const std::string& filepath) {
        if (resource_system_initialized && shouldUseResourcePack(filepath)) {
            auto& loader = ResourceLoader::getInstance();
            std::string pack_path = getPackPath(filepath);

            auto data = loader.loadResource(pack_path);
            if (!data.empty()) {
                return data;
            }
        }

        std::ifstream file(filepath, std::ios::binary | std::ios::ate);
        if (!file) {
            return {};
        }

        std::streamsize file_size = file.tellg();
        file.seekg(0, std::ios::beg);

        std::vector<uint8_t> data(file_size);
        if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
            return {};
        }

        return data;
    }

    bool shouldUseResourcePack(const std::string& filepath) {
        // Solo entran al pack los ficheros dentro de data/
        return filepath.find("data/") != std::string::npos;
    }

    std::string getPackPath(const std::string& asset_path) {
        std::string pack_path = asset_path;
        std::replace(pack_path.begin(), pack_path.end(), '\\', '/');

        // Toma la última aparición de "data/" como prefijo a quitar
        size_t last_data = pack_path.rfind("data/");
        if (last_data != std::string::npos) {
            pack_path = pack_path.substr(last_data + 5);
        }
        return pack_path;
    }
}  // namespace ResourceHelper
