package com.firefrostgaming.bitchbot;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

/**
 * Writes a YAWP (Yet Another World Protection) region config file directly
 * to disk in world/serverconfig/. Per Gemini's Q1 architecture: NO commands,
 * NO RCON — just a JSON file the YAWP mod picks up at next world load.
 *
 * The file format is intentionally simple and matches the schema YAWP expects
 * for region definitions. If the on-disk format diverges, this is the ONE
 * place to fix it (the rest of Bitch Bot won't change).
 *
 * Output: world/serverconfig/yawp/regions/{regionName}.json
 */
public class YawpConfigWriter {

    public static void write(Path serverRoot, ProvisionConfig.YawpRegion region, String dimensionId) throws Exception {
        Path regionsDir = serverRoot.resolve("world").resolve("serverconfig").resolve("yawp").resolve("regions");
        Files.createDirectories(regionsDir);

        JsonObject root = new JsonObject();
        root.addProperty("name", region.name);
        root.addProperty("dimension", dimensionId);

        JsonObject min = new JsonObject();
        min.addProperty("x", region.min.x);
        min.addProperty("y", region.min.y);
        min.addProperty("z", region.min.z);
        root.add("min", min);

        JsonObject max = new JsonObject();
        max.addProperty("x", region.max.x);
        max.addProperty("y", region.max.y);
        max.addProperty("z", region.max.z);
        root.add("max", max);

        JsonArray flags = new JsonArray();
        if (region.flags != null) for (String f : region.flags) flags.add(f);
        root.add("flags", flags);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Path outFile = regionsDir.resolve(region.name + ".json");
        Files.writeString(outFile, gson.toJson(root),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        BitchBot.LOGGER.info("[BitchBot] YAWP region '{}' written → {}", region.name, outFile);
    }
}
