import { existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { applyEdits, modify } from "jsonc-parser";
import { format } from "prettier";
import { ZUPLO_FALLBACK_JSON_FILE, ZUPLO_PREFERRED_JSON_FILE, ZUPLO_SYSTEM_ENV_VAR, } from "../common/constants.js";
import { logger } from "../common/logger.js";
import { printCriticalFailureToConsoleAndExit } from "../common/output.js";
import settings from "../common/settings.js";
export async function safeMergeConfig(dir, project) {
    const normalizedDir = join(relative(process.cwd(), dir));
    const zuploPreferredConfigFile = join(normalizedDir, ZUPLO_PREFERRED_JSON_FILE);
    const zuploFallbackConfigFile = join(normalizedDir, ZUPLO_FALLBACK_JSON_FILE);
    if (existsSync(zuploPreferredConfigFile)) {
        const originalContents = await readFile(zuploPreferredConfigFile, "utf-8");
        const modifyProjectEdit = modify(originalContents, ["project"], project, {
            getInsertionIndex: () => 2,
        });
        const contentsPostProject = applyEdits(originalContents, modifyProjectEdit);
        const formatted = await format(contentsPostProject, {
            parser: "json",
            quoteProps: "as-needed",
        });
        await writeFile(zuploPreferredConfigFile, formatted);
    }
    else if (existsSync(zuploFallbackConfigFile)) {
        const config = JSON.parse(await readFile(zuploFallbackConfigFile, "utf-8"));
        const formatted = await format(JSON.stringify({
            version: 1,
            project: project,
            compatibilityDate: config.compatibilityDate,
        }), {
            parser: "json",
            quoteProps: "as-needed",
        });
        await writeFile(zuploPreferredConfigFile, formatted);
    }
    else {
        const formatted = await format(JSON.stringify({
            version: 1,
            project: project,
            compatibilityDate: "2023-03-14",
        }), {
            parser: "json",
            quoteProps: "as-needed",
        });
        await writeFile(zuploPreferredConfigFile, formatted);
    }
}
export async function pullSystemConfig(argv) {
    const normalizedDir = join(relative(process.cwd(), argv.dir));
    const zuploPreferredConfigFile = join(normalizedDir, ZUPLO_SYSTEM_ENV_VAR);
    const environmentResponseFromDeveloperAPI = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/environments/${argv.environment}/configurations`, {
        headers: {
            authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (!environmentResponseFromDeveloperAPI.ok) {
        if (environmentResponseFromDeveloperAPI.status === 404 ||
            environmentResponseFromDeveloperAPI.status === 401) {
            await printCriticalFailureToConsoleAndExit("Error: Failed to link data from the environment. The environment you specified doesn't exist or you don't have access to it.");
        }
        else {
            logger.error({
                status: environmentResponseFromDeveloperAPI.status,
                statusText: environmentResponseFromDeveloperAPI.statusText,
            }, `Failed to link data from ${argv.environment}`);
            await printCriticalFailureToConsoleAndExit("Error: Failed to link data from the environment. Please try again later.");
        }
    }
    const payload = await environmentResponseFromDeveloperAPI.json();
    const content = `
# This file is auto-generated from zuplo link. Please do not edit it manually.
# It will be auto-generated afresh the next time you run zuplo link.
# If you wish to add your own environment variables, create a separate .env file.

ZUPLO_ACCOUNT_NAME=${payload.accountName}
ZUPLO_PROJECT_NAME=${payload.projectName}
ZUPLO_ENVIRONMENT_TYPE=${payload.environmentType}
ZUPLO_SYSTEM_CONFIGURATIONS=${payload["systemConfigurations"]}
`;
    await writeFile(zuploPreferredConfigFile, content);
}
//# sourceMappingURL=populate.js.map