import { existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { parse } from "jsonc-parser";
import { format } from "prettier";
import { StandardUpgrader, VsCodeFolderMissing } from "./lib.js";
const zuploSchemas = [
    {
        fileMatch: ["config/*.oas.json"],
        url: "https://cdn.zuplo.com/schemas/openapi-v3.1-zuplo.json",
    },
    {
        fileMatch: ["config/policies.json"],
        url: "https://cdn.zuplo.com/schemas/policies.json",
    },
    {
        fileMatch: ["config/dev-portal.json"],
        url: "https://cdn.zuplo.com/schemas/dev-portal.json",
    },
    {
        fileMatch: ["docs/sidebar.json"],
        url: "https://cdn.zuplo.com/schemas/sidebar.json",
    },
];
export class VsCodeSettingsJsonUpgrader extends StandardUpgrader {
    async isApplicable() {
        const vsCodeFolder = join(this.normalizedDir, ".vscode");
        if (existsSync(vsCodeFolder)) {
            return { ok: true };
        }
        else {
            return { ok: false, error: new VsCodeFolderMissing() };
        }
    }
    async upgrade() {
        const vsCodeSettingsFile = join(this.normalizedDir, ".vscode", "settings.json");
        if (!existsSync(vsCodeSettingsFile)) {
            const content = `
{
"json.schemas": [
    {
    "fileMatch": ["config/*.oas.json"],
    "url": "https://cdn.zuplo.com/schemas/openapi-v3.1-zuplo.json"
    },
    {
    "fileMatch": ["config/policies.json"],
    "url": "https://cdn.zuplo.com/schemas/policies.json"
    },
    {
    "fileMatch": ["config/dev-portal.json"],
    "url": "https://cdn.zuplo.com/schemas/dev-portal.json"
    },
    {
    "fileMatch": ["docs/sidebar.json"],
    "url": "https://cdn.zuplo.com/schemas/sidebar.json"
    }
]
}`;
            const formatted = await format(content, {
                parser: "json",
                quoteProps: "as-needed",
            });
            await writeFile(vsCodeSettingsFile, formatted);
        }
        else {
            const settingsRaw = await readFile(vsCodeSettingsFile, "utf-8");
            const settingsJson = parse(settingsRaw, [], { allowTrailingComma: true });
            for (const schema of zuploSchemas) {
                const existingSchema = settingsJson["json.schemas"].find((s) => s.fileMatch[0] === schema.fileMatch[0]);
                if (existingSchema) {
                    existingSchema.url = schema.url;
                }
                else {
                    settingsJson["json.schemas"].push(schema);
                }
            }
            const formatted = await format(JSON.stringify(settingsJson), {
                parser: "json",
                quoteProps: "as-needed",
            });
            await writeFile(vsCodeSettingsFile, formatted);
        }
    }
}
//# sourceMappingURL=vscode-settings-json-upgrader.js.map