"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addOrUpdateEnvironmentVariablesStep = addOrUpdateEnvironmentVariablesStep;
const chalk_1 = __importDefault(require("chalk"));
const telemetry_1 = require("../telemetry");
const analytics_1 = require("../utils/analytics");
const ui_1 = require("../ui");
const file_utils_1 = require("../utils/file-utils");
const fs = __importStar(require("fs"));
const path_1 = __importDefault(require("path"));
async function addOrUpdateEnvironmentVariablesStep({ installDir, variables, integration, }) {
    return (0, telemetry_1.traceStep)('add-or-update-environment-variables', async () => {
        const envVarContent = Object.entries(variables)
            .map(([key, value]) => `${key}=${value}`)
            .join('\n');
        const dotEnvLocalFilePath = path_1.default.join(installDir, '.env.local');
        const dotEnvFilePath = path_1.default.join(installDir, '.env');
        const targetEnvFilePath = fs.existsSync(dotEnvLocalFilePath)
            ? dotEnvLocalFilePath
            : dotEnvFilePath;
        const dotEnvFileExists = fs.existsSync(targetEnvFilePath);
        const relativeEnvFilePath = path_1.default.relative(installDir, targetEnvFilePath);
        let addedGitignore = false;
        let addedEnvVariables = false;
        if (dotEnvFileExists) {
            try {
                let dotEnvFileContent = fs.readFileSync(targetEnvFilePath, 'utf8');
                let updated = false;
                for (const [key, value] of Object.entries(variables)) {
                    const regex = new RegExp(`^${key}=.*$`, 'm');
                    if (dotEnvFileContent.match(regex)) {
                        dotEnvFileContent = dotEnvFileContent.replace(regex, `${key}=${value}`);
                        updated = true;
                    }
                    else {
                        if (!dotEnvFileContent.endsWith('\n')) {
                            dotEnvFileContent += '\n';
                        }
                        dotEnvFileContent += `${key}=${value}\n`;
                        updated = true;
                    }
                }
                if (updated) {
                    await fs.promises.writeFile(targetEnvFilePath, dotEnvFileContent, {
                        encoding: 'utf8',
                        flag: 'w',
                    });
                    (0, ui_1.getUI)().log.success(`Updated environment variables in ${chalk_1.default.bold.cyan(relativeEnvFilePath)}`);
                }
                else {
                    (0, ui_1.getUI)().log.success(`${chalk_1.default.bold.cyan(relativeEnvFilePath)} already has the necessary environment variables.`);
                }
                addedEnvVariables = true;
            }
            catch (error) {
                (0, ui_1.getUI)().log.warn(`Failed to update environment variables in ${chalk_1.default.bold.cyan(relativeEnvFilePath)}. Please update them manually.`);
                (0, analytics_1.captureWizardError)('Environment Variables', error instanceof Error ? error.message : 'Unknown error', 'add-or-update-env:update-existing', { integration });
                return {
                    relativeEnvFilePath,
                    addedEnvVariables,
                    addedGitignore,
                };
            }
        }
        else {
            try {
                await fs.promises.writeFile(targetEnvFilePath, envVarContent, {
                    encoding: 'utf8',
                    flag: 'w',
                });
                (0, ui_1.getUI)().log.success(`Created ${chalk_1.default.bold.cyan(relativeEnvFilePath)} with environment variables.`);
                addedEnvVariables = true;
            }
            catch (error) {
                (0, ui_1.getUI)().log.warn(`Failed to create ${chalk_1.default.bold.cyan(relativeEnvFilePath)} with environment variables. Please add them manually.`);
                (0, analytics_1.captureWizardError)('Environment Variables', error instanceof Error ? error.message : 'Unknown error', 'add-or-update-env:create-new', { integration });
                return {
                    relativeEnvFilePath,
                    addedEnvVariables,
                    addedGitignore,
                };
            }
        }
        const gitignorePath = (0, file_utils_1.getDotGitignore)({ installDir });
        const envFileName = path_1.default.basename(targetEnvFilePath);
        const envFiles = [envFileName];
        if (gitignorePath) {
            const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
            const missingEnvFiles = envFiles.filter((file) => !gitignoreContent.includes(file));
            if (missingEnvFiles.length > 0) {
                try {
                    const newGitignoreContent = `${gitignoreContent}\n${missingEnvFiles.join('\n')}`;
                    await fs.promises.writeFile(gitignorePath, newGitignoreContent, {
                        encoding: 'utf8',
                        flag: 'w',
                    });
                    (0, ui_1.getUI)().log.success(`Updated ${chalk_1.default.bold.cyan('.gitignore')} to include ${chalk_1.default.bold.cyan(envFileName)}.`);
                    addedGitignore = true;
                }
                catch (error) {
                    (0, ui_1.getUI)().log.warn(`Failed to update ${chalk_1.default.bold.cyan('.gitignore')} to include ${chalk_1.default.bold.cyan(envFileName)}.`);
                    (0, analytics_1.captureWizardError)('Environment Variables', error instanceof Error ? error.message : 'Unknown error', 'add-or-update-env:gitignore-update', { integration });
                    return {
                        relativeEnvFilePath,
                        addedEnvVariables,
                        addedGitignore,
                    };
                }
            }
        }
        else {
            try {
                const newGitignoreContent = `${envFiles.join('\n')}\n`;
                await fs.promises.writeFile(path_1.default.join(installDir, '.gitignore'), newGitignoreContent, {
                    encoding: 'utf8',
                    flag: 'w',
                });
                (0, ui_1.getUI)().log.success(`Created ${chalk_1.default.bold.cyan('.gitignore')} with environment files.`);
                addedGitignore = true;
            }
            catch (error) {
                (0, ui_1.getUI)().log.warn(`Failed to create ${chalk_1.default.bold.cyan('.gitignore')} with environment files.`);
                (0, analytics_1.captureWizardError)('Environment Variables', error instanceof Error ? error.message : 'Unknown error', 'add-or-update-env:gitignore-create', { integration });
                return {
                    relativeEnvFilePath,
                    addedEnvVariables,
                    addedGitignore,
                };
            }
        }
        analytics_1.analytics.wizardCapture('environment variables added', {
            integration,
        });
        return {
            relativeEnvFilePath,
            addedEnvVariables,
            addedGitignore,
        };
    });
}
