#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_;
        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(file_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_.loadPack(pack_file);

        if (pack_loaded_) {
            std::cout << "ResourceHelper: pack loaded (" << pack_.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_.clear();
        pack_loaded_ = false;
    }

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

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

}  // namespace ResourceHelper
