/**
 * src/utils/discover-env.ts
 *
 * First-run env-key discovery. The npm-global binary has no .env of its
 * own, but most users already have one lying around — usually in a
 * development clone of the repo (~/Projects/muassis-gateway/.env), or in
 * ~/.muassis.env. Without this, the user has to manually copy keys into
 * <dataDir>/.env, which they shouldn't have to know about.
 *
 * On every gateway boot (and `muassis init`), if the persistent
 * <dataDir>/.env doesn't already have an NVIDIA key, we silently sweep a
 * handful of likely locations and migrate the first key we find. Result
 * is logged in one line so the user can see what just happened.
 */
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
// Keys we're willing to import. Restricted to model/email/secret values —
// nothing channel-specific or tenant-bound, so we never copy state from
// one local project into another.
const IMPORT_KEYS = new Set([
    'NVIDIA_API_KEY', 'NVIDIA_NIM_API_KEY', 'NVIDIA_NIM_BASE_URL',
    'OPENAI_API_KEY',
    'EMAIL_RESEND_API_KEY', 'EMAIL_FROM',
    'SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS', 'SMTP_SECURE',
    'AZURE_TTS_KEY', 'AZURE_TTS_REGION',
    'ELEVENLABS_API_KEY',
]);
function parseEnvFile(path) {
    if (!existsSync(path))
        return {};
    let body;
    try {
        body = readFileSync(path, 'utf-8');
    }
    catch {
        return {};
    }
    const out = {};
    for (const rawLine of body.split('\n')) {
        const line = rawLine.trim();
        if (!line || line.startsWith('#'))
            continue;
        const m = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
        if (!m)
            continue;
        let v = m[2].trim();
        if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
            v = v.slice(1, -1);
        }
        out[m[1]] = v;
    }
    return out;
}
function writeEnvFile(path, entries) {
    mkdirSync(join(path, '..'), { recursive: true });
    const keys = Object.keys(entries).sort();
    const body = keys.map((k) => {
        const v = entries[k] ?? '';
        const needsQuote = /[\s#]/.test(v);
        return `${k}=${needsQuote ? `"${v.replace(/"/g, '\\"')}"` : v}`;
    }).join('\n') + '\n';
    writeFileSync(path, body, { mode: 0o600 });
}
/** Candidate .env files in priority order. First one with a NIM key wins. */
function candidatePaths() {
    const home = homedir();
    const fixed = [
        join(home, 'Projects', 'muassis-gateway', '.env'),
        join(home, 'Projects', 'muassis', '.env'),
        join(home, 'Documents', 'muassis-gateway', '.env'),
        join(home, 'Desktop', 'muassis-gateway', '.env'),
        join(home, 'code', 'muassis-gateway', '.env'),
        join(home, '.muassis.env'),
        join(process.cwd(), '.env'),
    ];
    // Sweep ~/Projects/*/.env one level deep — catches user setups like
    // ~/Projects/muassis-fork/.env or ~/Projects/al-moasis/.env without
    // hardcoding every name we can imagine.
    const projectsDir = join(home, 'Projects');
    const sweptPaths = [];
    if (existsSync(projectsDir)) {
        try {
            for (const entry of readdirSync(projectsDir)) {
                const full = join(projectsDir, entry);
                try {
                    if (!statSync(full).isDirectory())
                        continue;
                }
                catch {
                    continue;
                }
                sweptPaths.push(join(full, '.env'));
            }
        }
        catch {
            // permission denied / weird FS — ignore, fall back to fixed list
        }
    }
    // Dedupe while preserving order
    const seen = new Set();
    const merged = [...fixed, ...sweptPaths].filter(p => {
        if (seen.has(p))
            return false;
        seen.add(p);
        return true;
    });
    return merged;
}
/**
 * If <dataDir>/.env already has NVIDIA_API_KEY (or NVIDIA_NIM_API_KEY),
 * do nothing. Otherwise scan candidate paths, find the first .env that
 * has a NIM key, copy the IMPORT_KEYS subset into <dataDir>/.env, and
 * also seed them into process.env so the current run uses them too.
 */
export function discoverAndMigrateEnv(dataDir) {
    const destPath = join(dataDir, '.env');
    const existing = parseEnvFile(destPath);
    if (existing.NVIDIA_API_KEY || existing.NVIDIA_NIM_API_KEY) {
        return { imported: false, sourcePath: null, keysImported: [], destPath };
    }
    for (const candidate of candidatePaths()) {
        if (candidate === destPath)
            continue;
        const parsed = parseEnvFile(candidate);
        const hasKey = parsed.NVIDIA_API_KEY || parsed.NVIDIA_NIM_API_KEY;
        if (!hasKey)
            continue;
        const merged = { ...existing };
        const imported = [];
        for (const [k, v] of Object.entries(parsed)) {
            if (!IMPORT_KEYS.has(k))
                continue;
            if (!v)
                continue;
            if (merged[k] === v)
                continue;
            merged[k] = v;
            imported.push(k);
            // Seed live process.env too so the current boot picks them up
            // without needing a restart.
            if (!process.env[k])
                process.env[k] = v;
        }
        if (imported.length === 0)
            continue;
        writeEnvFile(destPath, merged);
        return { imported: true, sourcePath: candidate, keysImported: imported, destPath };
    }
    return { imported: false, sourcePath: null, keysImported: [], destPath };
}
//# sourceMappingURL=discover-env.js.map