#include <DevCommand/MkWorldCommand/MkWorldCommand.hpp>
#include <Log/Log.hpp>
#include <AtomicDataStore/AtomicDataStore.hpp>
#include <WorldIndex/WorldIndex.hpp>
#include <WorldType/SurvivalWorldType/SurvivalWorldType.hpp>
#include <WorldTypeRegistry/WorldTypeRegistry.hpp>

int MkWorldCommand::execute(const std::vector<std::string> &args)
{
    if (args.size() < 4)
    {
        Log::error("Syntax: mkworld <filename> <type> [options...]");
        return 1;
    }

    const std::string &path = args[2];
    const std::string &typeID = args[3];

    WorldType *worldType = worldTypeRegistry.getByID(typeID);
    if (worldType == nullptr)
    {
        Log::error("Unknown world type.");
        return 1;
    }

    WorldIndex worldIndex = WorldIndex::create(false, WorldAvatar::Voxelverse);
    std::shared_ptr<WorldTypeSettings> settings = worldType->parseSettingsFromCmdArgs(args.data() + 4, args.size() - 4);
    if (settings == nullptr)
    {
        return 1;
    }

    worldIndex.setSettings(typeID, *settings);

    AtomicDataStore store;
    store.create(path);
    const std::string &storeError = store.getError();

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

    AtomicDataStore::Plan plan;
    serializeInto(plan["windex.dat"], worldIndex);
    store.update(plan, 0);

    Log::info("World created successfully.");
    return 0;
}