// pack_resources.cpp - Utilitat per crear paquets de recursos
// © 2025 Orni Attack

#include "../../source/core/resources/resource_pack.hpp"

#include <filesystem>
#include <iostream>

void print_usage(const char* program_name) {
    std::cout << "Ús: " << program_name << " [opcions] [directori_entrada] [fitxer_sortida]\n";
    std::cout << "\nOpcions:\n";
    std::cout << "  --list <fitxer>    Llistar contingut d'un paquet\n";
    std::cout << "\nExemples:\n";
    std::cout << "  " << program_name << " data resources.pack\n";
    std::cout << "  " << program_name << " --list resources.pack\n";
    std::cout << "\nSi no s'especifiquen arguments, empaqueta 'data/' a 'resources.pack'\n";
}

int main(int argc, char* argv[]) {
    std::string input_dir = "data";
    std::string output_file = "resources.pack";

    // Processar arguments
    if (argc == 2 && std::string(argv[1]) == "--help") {
        print_usage(argv[0]);
        return 0;
    }

    // Mode --list
    if (argc == 3 && std::string(argv[1]) == "--list") {
        Resource::Pack pack;
        if (!pack.loadPack(argv[2])) {
            std::cerr << "ERROR: No es pot carregar " << argv[2] << "\n";
            return 1;
        }

        std::cout << "Contingut de " << argv[2] << ":\n";
        auto resources = pack.getResourceList();
        std::cout << "Total: " << resources.size() << " recursos\n\n";

        for (const auto& name : resources) {
            std::cout << "  " << name << "\n";
        }

        return 0;
    }

    // Mode empaquetar
    if (argc >= 3) {
        input_dir = argv[1];
        output_file = argv[2];
    }

    // Verificar que existeix el directori
    if (!std::filesystem::exists(input_dir)) {
        std::cerr << "ERROR: Directori no trobat: " << input_dir << "\n";
        return 1;
    }

    if (!std::filesystem::is_directory(input_dir)) {
        std::cerr << "ERROR: " << input_dir << " no és un directori\n";
        return 1;
    }

    // Crear paquet
    std::cout << "Creant paquet de recursos...\n";
    std::cout << "  Entrada: " << input_dir << "\n";
    std::cout << "  Sortida: " << output_file << "\n\n";

    Resource::Pack pack;
    if (!pack.addDirectory(input_dir)) {
        std::cerr << "ERROR: No s'ha pogut afegir el directori\n";
        return 1;
    }

    if (!pack.savePack(output_file)) {
        std::cerr << "ERROR: No s'ha pogut guardar el paquet\n";
        return 1;
    }

    // Resum
    auto resources = pack.getResourceList();
    std::cout << "\n";
    std::cout << "✓ Paquet creat amb èxit!\n";
    std::cout << "  Recursos: " << resources.size() << "\n";

    // Mostrar mida del fitxer
    auto file_size = std::filesystem::file_size(output_file);
    std::cout << "  Mida: " << (file_size / 1024) << " KB\n";

    return 0;
}
