"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadRtwsDotenv = loadRtwsDotenv;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function isEnvKeyValid(key) {
    return /^[A-Za-z_][A-Za-z0-9_]*$/.test(key);
}
function unescapeDoubleQuoted(value) {
    let out = '';
    for (let i = 0; i < value.length; i++) {
        const ch = value[i];
        if (ch !== '\\') {
            out += ch;
            continue;
        }
        const next = value[i + 1];
        if (next === undefined) {
            out += '\\';
            continue;
        }
        i++;
        if (next === 'n')
            out += '\n';
        else if (next === 'r')
            out += '\r';
        else if (next === 't')
            out += '\t';
        else if (next === '\\')
            out += '\\';
        else if (next === '"')
            out += '"';
        else
            out += next;
    }
    return out;
}
function stripInlineCommentFromUnquotedValue(raw) {
    // Strip `# ...` only when it is preceded by whitespace.
    for (let i = 0; i < raw.length; i++) {
        const ch = raw[i];
        if (ch !== '#')
            continue;
        if (i === 0)
            return '';
        const prev = raw[i - 1];
        if (prev === ' ' || prev === '\t')
            return raw.slice(0, i).trimEnd();
    }
    return raw.trimEnd();
}
function parseLine(line) {
    const trimmed = line.trim();
    if (trimmed.length === 0)
        return { kind: 'skip' };
    if (trimmed.startsWith('#'))
        return { kind: 'skip' };
    const withoutExport = trimmed.startsWith('export ')
        ? trimmed.slice('export '.length).trim()
        : trimmed;
    const equalsIndex = withoutExport.indexOf('=');
    if (equalsIndex < 0)
        return { kind: 'error', reason: 'missing_equals' };
    const rawKey = withoutExport.slice(0, equalsIndex).trim();
    if (rawKey.length === 0)
        return { kind: 'error', reason: 'empty_key' };
    if (!isEnvKeyValid(rawKey))
        return { kind: 'error', reason: 'invalid_key' };
    let rawValue = withoutExport.slice(equalsIndex + 1).trim();
    if (rawValue.length >= 2 && rawValue.startsWith('"') && rawValue.endsWith('"')) {
        rawValue = unescapeDoubleQuoted(rawValue.slice(1, -1));
    }
    else if (rawValue.length >= 2 && rawValue.startsWith("'") && rawValue.endsWith("'")) {
        rawValue = rawValue.slice(1, -1);
    }
    else {
        rawValue = stripInlineCommentFromUnquotedValue(rawValue);
    }
    return { kind: 'entry', key: rawKey, value: rawValue };
}
function loadRtwsDotenv(params) {
    const cwd = params && typeof params.cwd === 'string' ? params.cwd : process.cwd();
    const files = ['.env', '.env.local'];
    const loadedFiles = [];
    const errors = [];
    for (const file of files) {
        const absPath = path.join(cwd, file);
        if (!fs.existsSync(absPath))
            continue;
        loadedFiles.push(file);
        const content = fs.readFileSync(absPath, 'utf8');
        const lines = content.split(/\r?\n/);
        for (let i = 0; i < lines.length; i++) {
            const raw = lines[i];
            const parsed = parseLine(raw);
            if (parsed.kind === 'skip')
                continue;
            if (parsed.kind === 'error') {
                errors.push({ file, lineNumber: i + 1, raw, reason: parsed.reason });
                continue;
            }
            if (parsed.kind === 'entry') {
                process.env[parsed.key] = parsed.value;
                continue;
            }
            const _exhaustive = parsed;
            throw new Error(`Unexpected dotenv parse result: ${String(_exhaustive)}`);
        }
    }
    return { cwd, loadedFiles, errors };
}
