#include "resource_manager.hpp"
#include "resource_pack.hpp"

#include <iostream>
#include <fstream>
#include <cstring>

// Inicializar estáticos
ResourcePack* ResourceManager::resourcePack_ = nullptr;
std::map<std::string, std::vector<unsigned char>> ResourceManager::cache_;

bool ResourceManager::init(const std::string& packFilePath) {
    // Si ya estaba inicializado, liberar primero
    if (resourcePack_ != nullptr) {
        delete resourcePack_;
        resourcePack_ = nullptr;
    }

    // Intentar cargar el pack
    resourcePack_ = new ResourcePack();
    if (!resourcePack_->loadPack(packFilePath)) {
        // Si falla, borrar instancia (usará fallback a disco)
        delete resourcePack_;
        resourcePack_ = nullptr;
        std::cout << "resources.pack no encontrado - usando carpeta data/" << std::endl;
        return false;
    }

    std::cout << "resources.pack cargado (" << resourcePack_->getResourceCount() << " recursos)" << std::endl;
    return true;
}

void ResourceManager::shutdown() {
    cache_.clear();
    if (resourcePack_ != nullptr) {
        delete resourcePack_;
        resourcePack_ = nullptr;
    }
}

bool ResourceManager::loadResource(const std::string& resourcePath, unsigned char*& data, size_t& size) {
    data = nullptr;
    size = 0;

    // 1. Consultar caché en RAM (sin I/O)
    auto it = cache_.find(resourcePath);
    if (it != cache_.end()) {
        size = it->second.size();
        data = new unsigned char[size];
        std::memcpy(data, it->second.data(), size);
        return true;
    }

    // 2. Intentar cargar desde pack (si está disponible)
    if (resourcePack_ != nullptr) {
        ResourcePack::ResourceData packData = resourcePack_->loadResource(resourcePath);
        if (packData.data != nullptr) {
            cache_[resourcePath] = std::vector<unsigned char>(packData.data, packData.data + packData.size);
            data = packData.data;
            size = packData.size;
            return true;
        }
    }

    // 3. Fallback: cargar desde disco
    std::ifstream file(resourcePath, std::ios::binary | std::ios::ate);
    if (!file) {
        std::string dataPath = "data/" + resourcePath;
        file.open(dataPath, std::ios::binary | std::ios::ate);
        if (!file) { return false; }
    }
    size = static_cast<size_t>(file.tellg());
    file.seekg(0, std::ios::beg);
    data = new unsigned char[size];
    file.read(reinterpret_cast<char*>(data), size);
    file.close();

    // Guardar en caché
    cache_[resourcePath] = std::vector<unsigned char>(data, data + size);
    return true;
}

bool ResourceManager::isPackLoaded() {
    return resourcePack_ != nullptr;
}

std::vector<std::string> ResourceManager::getResourceList() {
    if (resourcePack_ != nullptr) {
        return resourcePack_->getResourceList();
    }
    return std::vector<std::string>();  // Vacío si no hay pack
}

size_t ResourceManager::getResourceCount() {
    if (resourcePack_ != nullptr) {
        return resourcePack_->getResourceCount();
    }
    return 0;
}
