import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { ZUPLO_SYSTEM_ENV_VAR } from "./constants.js";
import { logger } from "./logger.js";
import { printCriticalFailureToConsoleAndExit } from "./output.js";
import settings from "./settings.js";
const SYSTEM_KEYS = [
    "accountName",
    "projectName",
    "environmentType",
    "systemConfigurations",
];
function wrapEnvValue(value) {
    const escapedValue = value.replace(/"/g, '\\"');
    return `"${escapedValue}"`;
}
export async function pullSystemConfig(argv) {
    const normalizedDir = resolve(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);
}
export async function pullLocalConfig(argv) {
    const normalizedDir = resolve(argv.dir);
    const zuploPreferredConfigFile = join(normalizedDir, ZUPLO_SYSTEM_ENV_VAR);
    const environmentResponseFromDeveloperAPI = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/environments/${argv.environment}/local-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 userEnvVars = Object.keys(payload)
        .filter((key) => {
        return !key.startsWith("ZUPLO_PUBLIC_") && !SYSTEM_KEYS.includes(key);
    })
        .map((key) => {
        return `${key}=${wrapEnvValue(payload[key])}`;
    });
    const zuploPublicEnvVars = Object.keys(payload)
        .filter((key) => {
        return key.startsWith("ZUPLO_PUBLIC_");
    })
        .map((key) => {
        return `${key}=${wrapEnvValue(payload[key])}`;
    });
    let 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"]}`;
    if (zuploPublicEnvVars.length > 0) {
        content += `

# Public Zuplo environment variables
${zuploPublicEnvVars.join("\n")}`;
    }
    if (userEnvVars.length > 0) {
        content += `

# Environment variables defined in the Zuplo UI for the environment
# Note that " characters are escaped with a backslash and escaped double quotes
# will show up as \\" in the value.
${userEnvVars.join("\n")}`;
    }
    content += "\n";
    await writeFile(zuploPreferredConfigFile, content);
}
//# sourceMappingURL=populate.js.map