/**
 * src/utils/load-env.ts
 *
 * Find and load the user's .env file from a set of stable locations.
 *
 * The challenge: when Muassis is installed globally (`npm install -g`), the
 * package lives somewhere like `/usr/local/lib/node_modules/@almoasisai/...`
 * and that directory has no .env (we don't ship one). So the gateway boots
 * with no NVIDIA_API_KEY, falls back to the public proxy, and hits its 25s
 * function-invocation cap on any non-trivial turn.
 *
 * The fix: look for .env in the platform-native data dir (the same place
 * `muassis init` saves owner.id and the SQLite database). Users put their
 * keys there once and they survive reinstalls / version bumps.
 *
 * Search order (first match wins, no merging):
 *   1. $MUASSIS_DOTENV       — explicit override
 *   2. <dataDir>/.env        — platform-native config (recommended)
 *   3. $HOME/.muassis.env    — legacy
 *   4. process.cwd()/.env    — running `muassis` from a project dir
 *   5. <packageRoot>/.env    — development checkout fallback
 */
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir, platform } from 'node:os';
import { config as dotenvConfig } from 'dotenv';
import { discoverAndMigrateEnv } from './discover-env.js';
// IMPORTANT: these MUST match getDataDir() in data-dir.ts. The v3 rebrand
// renamed the data dir Muassis → AlMoasis everywhere EXCEPT here, so BYOK
// keys (written to AlMoasis/.env) were never loaded at boot — the brain
// silently stayed on the bundled key. We can't import getDataDir (circular:
// load-env → data-dir → config → load-env), so the name is duplicated and
// the legacy Muassis dir is kept as a fallback candidate below.
function platformDataDir() {
    if (process.env.MUASSIS_DATA_DIR)
        return process.env.MUASSIS_DATA_DIR;
    const home = homedir();
    switch (platform()) {
        case 'darwin':
            return join(home, 'Library', 'Application Support', 'AlMoasis');
        case 'win32':
            return join(process.env.APPDATA ?? join(home, 'AppData', 'Roaming'), 'AlMoasis');
        default: {
            const xdg = process.env.XDG_DATA_HOME ?? join(home, '.local', 'share');
            return join(xdg, 'almoasis');
        }
    }
}
// Legacy (pre-v3) data dir, kept as a fallback .env source for old installs.
function legacyPlatformDataDir() {
    const home = homedir();
    switch (platform()) {
        case 'darwin':
            return join(home, 'Library', 'Application Support', 'Muassis');
        case 'win32':
            return join(process.env.APPDATA ?? join(home, 'AppData', 'Roaming'), 'Muassis');
        default: {
            const xdg = process.env.XDG_DATA_HOME ?? join(home, '.local', 'share');
            return join(xdg, 'muassis');
        }
    }
}
export function loadMuassisEnv(packageRoot) {
    const dataDir = platformDataDir();
    // First-run UX: if <dataDir>/.env doesn't have NVIDIA_API_KEY but the
    // user has one lying around in a dev clone (~/Projects/muassis-gateway/
    // .env, ~/.muassis.env, etc.), import it automatically. The user
    // shouldn't have to run a setup command to get the key in the right place.
    const discovery = discoverAndMigrateEnv(dataDir);
    if (discovery.imported) {
        // One-line breadcrumb so the user sees what just happened. Goes to
        // stderr so it doesn't break tools that capture stdout.
        const masked = process.env.NVIDIA_API_KEY ?? process.env.NVIDIA_NIM_API_KEY ?? '';
        const tail = masked.length > 10 ? masked.slice(-4) : '****';
        process.stderr.write(`[muassis] auto-imported config from ${discovery.sourcePath} → ${discovery.destPath} ` +
            `(keys: ${discovery.keysImported.join(', ')}; NIM key tail: …${tail})\n`);
    }
    const candidates = [
        process.env.MUASSIS_DOTENV ?? '',
        join(dataDir, '.env'), // primary: AlMoasis/.env (where BYOK writes)
        join(legacyPlatformDataDir(), '.env'), // legacy fallback: Muassis/.env
        join(homedir(), '.muassis.env'),
        join(process.cwd(), '.env'),
        packageRoot ? join(packageRoot, '.env') : '',
    ].filter(Boolean);
    for (const path of candidates) {
        if (existsSync(path)) {
            // override:false (default) preserves shell-set env vars over the file.
            dotenvConfig({ path, quiet: true });
            return { loaded: true, path, searchedPaths: candidates };
        }
    }
    return { loaded: false, path: null, searchedPaths: candidates };
}
//# sourceMappingURL=load-env.js.map