import { readFileSync, writeFileSync } from "fs";
import { editConfigJson, getConfigJsonPath } from "../util/paths.js";
function stringify(obj, indentation) {
    return JSON.stringify(obj, (key, value) => {
        return value === null ? undefined : value;
    }, indentation);
}
export function addModel(model) {
    const config = readFileSync(getConfigJsonPath(), "utf8");
    const configJson = JSON.parse(config);
    // De-duplicate
    if (configJson.models?.some((m) => stringify(m) === stringify(model))) {
        return config;
    }
    if (configJson.models?.some((m) => m?.title === model.title)) {
        model.title = `${model.title} (1)`;
    }
    configJson.models.push(model);
    const newConfigString = stringify(configJson, 2);
    writeFileSync(getConfigJsonPath(), newConfigString);
    return newConfigString;
}
export function addOpenAIKey(key) {
    editConfigJson((config) => {
        config.models = config.models
            .filter((model) => model.provider !== "free-trial" || model.model.startsWith("gpt"))
            .map((m) => {
            if (m.provider === "free-trial") {
                m.apiKey = key;
                m.provider = "openai";
            }
            return m;
        });
        return config;
    });
}
export function deleteModel(title) {
    editConfigJson((config) => {
        config.models = config.models.filter((m) => m.title !== title);
        return config;
    });
}
