#include <DevCommand/WRepackCommand/WRepackCommand.hpp>
#include <Log/Log.hpp>
#include <AtomicDataStore/AtomicDataStore.hpp>
#include <Utilities/Async.hpp>
#include <WorldAvatar/WorldAvatar.hpp>

int WRepackCommand::execute(const std::vector<std::string> &args)
{
    if (args.size() != 4)
    {
        Log::error("Syntax: wrepack <filename> <newfilename>");
        return 1;
    }

    std::string oldFilename = args[2];
    std::string newFilename = args[3];

    AtomicDataStore oldStore;
    if (!oldStore.open(oldFilename))
    {
        Log::error("Failed to open the old world file.");
        return 1;
    }

    std::vector<std::string> allFiles = oldStore.getAllFiles();
    AtomicDataStore::Plan plan;

    for (const std::string &file : allFiles)
    {
        Log::info(formatString("Reading $+...", file));
        if (!oldStore.read(file, plan[file]))
        {
            Log::error(formatString("Failed to read the file: $+", file));
            return 1;
        }
    }

    AtomicDataStore newStore;
    if (!newStore.create(newFilename))
    {
        Log::error("Failed to create the new world file.");
        return 1;
    }

    Log::info("Repacking...");
    newStore.update(plan, 0);

    size_t oldStoreSize = oldStore.file.size();
    size_t newStoreSize = newStore.file.size();

    Log::info(formatString(
        "Repack complete.\n"
        "  Old size:      $+\n"
        "  New size:      $+\n"
        "  Size decrease: $+%",
        formatDataSize(oldStoreSize),
        formatDataSize(newStoreSize),
        100 - (newStoreSize * 100 / oldStoreSize)
    ));
    
    return 0;
}