"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEnvPath = getEnvPath;
exports.readEnvFile = readEnvFile;
exports.getEnvVar = getEnvVar;
exports.writeEnvFile = writeEnvFile;
exports.setEnvVar = setEnvVar;
const constants_1 = require("../constants");
const path_resolver_1 = require("../schemas/io/path-resolver");
const dotenv_1 = require("dotenv");
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const path_1 = require("path");
/**
 * Get the path to agentcore/.env.local.
 * @param configRoot - Optional config root, defaults to finding it automatically
 */
function getEnvPath(configRoot) {
    const root = configRoot ?? (0, path_resolver_1.findConfigRoot)();
    if (!root)
        throw new Error('Could not find agentcore directory');
    return (0, path_1.join)(root, constants_1.ENV_FILE);
}
/**
 * Read agentcore/.env.local.
 */
async function readEnvFile(configRoot) {
    const path = getEnvPath(configRoot);
    if (!(0, fs_1.existsSync)(path))
        return {};
    return (0, dotenv_1.parse)(await (0, promises_1.readFile)(path, 'utf-8'));
}
/**
 * Get a single value from agentcore/.env.local.
 */
async function getEnvVar(key, configRoot) {
    return (await readEnvFile(configRoot))[key];
}
/**
 * Write to agentcore/.env.local. Merges with existing values by default.
 */
async function writeEnvFile(updates, configRoot, merge = true) {
    const path = getEnvPath(configRoot);
    const current = merge ? await readEnvFile(configRoot) : {};
    const env = { ...current, ...updates };
    const content = Object.entries(env)
        .map(([k, v]) => {
        if (v === undefined || v === null)
            return '';
        if (!/^[a-z_][a-z0-9_]*$/i.test(k))
            throw new Error(`Invalid env key: ${k}`);
        const val = String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
        return `${k}="${val}"`;
    })
        .filter(Boolean)
        .join('\n') + '\n';
    await (0, promises_1.writeFile)(path, content);
}
/**
 * Set a single value in agentcore/.env.local.
 */
async function setEnvVar(key, value, configRoot) {
    await writeEnvFile({ [key]: value }, configRoot);
}
//# sourceMappingURL=env.js.map