import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { parse } from "jsonc-parser";
import { ZUPLO_FALLBACK_JSON_FILE, ZUPLO_PREFERRED_JSON_FILE, } from "../constants.js";
import { logger } from "../logger.js";
import { printCriticalFailureToConsoleAndExit, printWarningToConsole, } from "../output.js";
import settings from "../settings.js";
export async function configure(argv) {
    const cliParametersConfiguration = { ...argv };
    const whoAmIResponse = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/who-am-i`, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (whoAmIResponse.ok) {
        const apiKeyMetadata = await whoAmIResponse.json();
        Object.assign(argv, omitNull(apiKeyMetadata));
        const { project: zuploJsoncProject } = await processZuploConfigurationFile(argv.dir);
        if (zuploJsoncProject) {
            printWarningToConsole("The project name in zuplo.jsonc is deprecated. Please remove the project key from zuplo.jsonc and use the --project flag or ZUPLO_PROJECT environment variable instead.");
            argv.project = zuploJsoncProject;
        }
        Object.assign(argv, cliParametersConfiguration);
    }
    else {
        logger.trace({ status: whoAmIResponse.status, statusText: whoAmIResponse.statusText }, "Failed to determine who-am-i");
        await printCriticalFailureToConsoleAndExit("Error: Failed to validate the API key. Check your API key.");
    }
}
async function processZuploConfigurationFile(sourceDirectory) {
    const normalizedDir = join(relative(process.cwd(), sourceDirectory ?? "."));
    const preferredPath = join(normalizedDir, ZUPLO_PREFERRED_JSON_FILE);
    const fallbackPath = join(normalizedDir, ZUPLO_FALLBACK_JSON_FILE);
    let fileContents = "{}";
    if (existsSync(preferredPath)) {
        fileContents = await readFile(preferredPath, "utf-8");
    }
    else if (existsSync(fallbackPath)) {
        fileContents = await readFile(fallbackPath, "utf-8");
    }
    else {
        logger.trace("No zuplo.jsonc file found");
        return {};
    }
    const errors = [];
    const data = parse(fileContents, errors, { allowTrailingComma: true });
    if (errors.length > 0) {
        logger.trace(errors[0], "Failed to parse zuplo.jsonc");
        await printCriticalFailureToConsoleAndExit("Error: Failed to parse the values from zuplo.jsonc. Check your zuplo.jsonc file.");
    }
    return data;
}
const omitNull = (obj) => {
    Object.keys(obj)
        .filter((k) => obj[k] === null)
        .forEach((k) => delete obj[k]);
    return obj;
};
//# sourceMappingURL=user-configuration.js.map