#include "core/resources/resource_helper.hpp"

#include <fstream>
#include <iostream>

#include "core/jail/jfile.hpp"
#include "core/resources/resource_pack.hpp"

namespace ResourceHelper {

    namespace {
        ResourcePack pack_obj;
        bool pack_loaded = false;
        bool fallback_enabled = true;

        auto readFromDisk(const std::string& relative_path) -> std::vector<uint8_t> {
            const std::string FULL = std::string(Jf::getResourceFolder()) + relative_path;
            std::ifstream file(FULL, std::ios::binary | std::ios::ate);
            if (!file) {
                return {};
            }

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

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

    auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback) -> bool {
        fallback_enabled = enable_fallback;
        pack_loaded = pack_obj.loadPack(pack_file);

        if (pack_loaded) {
            std::cout << "ResourceHelper: pack loaded (" << pack_obj.getResourceCount()
                      << " entries) from " << pack_file << '\n';
        } else if (enable_fallback) {
            std::cout << "ResourceHelper: no pack at " << pack_file
                      << " — using filesystem fallback\n";
        } else {
            std::cerr << "ResourceHelper: FATAL — no pack at " << pack_file
                      << " and fallback disabled\n";
            return false;
        }
        return true;
    }

    void shutdownResourceSystem() {
        pack_obj.clear();
        pack_loaded = false;
    }

    auto loadFile(const std::string& relative_path) -> std::vector<uint8_t> {
        if (pack_loaded && pack_obj.hasResource(relative_path)) {
            return pack_obj.getResource(relative_path);
        }
        if (fallback_enabled) {
            return readFromDisk(relative_path);
        }
        return {};
    }

    auto hasPack() -> bool {
        return pack_loaded;
    }

}  // namespace ResourceHelper
