package me.proxylink.plugin;

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;

public final class ConfigFileEditor {
    private ConfigFileEditor() {
    }

    public static void setProperty(Path path, String key, String value) throws IOException {
        List<String> lines = Files.exists(path)
                ? Files.readAllLines(path, StandardCharsets.UTF_8)
                : new ArrayList<>();

        String prefix = key + "=";
        boolean updated = false;
        for (int i = 0; i < lines.size(); i++) {
            String trimmed = lines.get(i).trim();
            if (!trimmed.startsWith("#") && trimmed.startsWith(prefix)) {
                lines.set(i, prefix + value);
                updated = true;
                break;
            }
        }

        if (!updated) {
            if (!lines.isEmpty() && !lines.get(lines.size() - 1).isBlank()) {
                lines.add("");
            }
            lines.add(prefix + value);
        }

        Files.write(path, lines, StandardCharsets.UTF_8);
    }
}
