package net.mcreator.phayriosisreborn.config;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/** One-time idempotent addition of a client-side modpack UI flag to legacy common TOMLs. */
public final class PhayriosisConfigUpgrade {
    private PhayriosisConfigUpgrade() {}

    /** Keep the existing GUI null-check as the single gate; no extra event listeners. */
    public static Object onlyIfVisible(Object buttonAnchor, boolean hidden) {
        return hidden ? null : buttonAnchor;
    }

    public static void ensureHideOption(Path path) throws IOException {
        List<String> lines = new ArrayList<>(Files.readAllLines(path, StandardCharsets.UTF_8));
        boolean general = false;
        int generalHeader = -1;
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i).trim();
            if (line.startsWith("[") && line.endsWith("]")) {
                general = line.equalsIgnoreCase("[general]");
                if (general) generalHeader = i;
            } else if (general) {
                int equal = line.indexOf('=');
                if (equal > 0 && line.substring(0, equal).trim().toLowerCase(Locale.ROOT)
                        .equals("hideworldcreationconfig")) return;
            }
        }
        List<String> additions = List.of(
                "# Modpack option: hide the Phayriosis settings button on the Create World screen.",
                "# Set true in the client instance's config/phayriosisreborn-common.toml before creating a world.",
                "# This is UI-only; per-world server config and admin commands still function normally.",
                "hideWorldCreationConfig = false");
        if (generalHeader >= 0) lines.addAll(generalHeader + 1, additions);
        else {
            lines.add("");
            lines.add("[general]");
            lines.addAll(additions);
        }
        Files.write(path, lines, StandardCharsets.UTF_8);
    }
}
