#include <DevCommand/WSetVersionCommand/WSetVersionCommand.hpp>
#include <Log/Log.hpp>
#include <AtomicDataStore/AtomicDataStore.hpp>

int WSetVersionCommand::execute(const std::vector<std::string> &args)
{
    if (args.size() != 4)
    {
        Log::error("SYNTAX: wsetversion <world-file> <version>");
        return 1;
    }

    std::string worldFilePath = args[2];
    std::string versionString = args[3];

    std::optional<Version> maybeVersion = Version::fromString(versionString);
    if (!maybeVersion.has_value())
    {
        Log::error(formatString("Invalid version string: $+", versionString));
        return 1;
    }

    Version newVersion = *maybeVersion;

    AtomicDataStore store;
    store.open(worldFilePath);
    const std::string &error = store.getError();

    if (!error.empty())
    {
        Log::error(error);
        return 1;
    }

    AtomicDataStore::Plan plan;
    std::vector<uint8_t> &windexBytes = plan["windex.dat"];
    if (!store.read("windex.dat", windexBytes))
    {
        Log::error("Failed to read the windex.dat file!");
        return 1;
    }

    if (windexBytes.size() < 8)
    {
        Log::error("windex.dat file too small to have a signature!");
        return 1;
    }

    windexBytes[5] = newVersion.major;
    windexBytes[6] = newVersion.minor;
    windexBytes[7] = newVersion.patchLevel;

    store.update(plan, 0);

    Log::info("Version updated successfully.");

    return 0;
}