/**

 * Ensure the default local dev API key works for Gateway /api/* routes.

 * - Postgres mode: seed key into DB (plain Node script, no tsx).

 * - Memory mode: Gateway must have API_KEY env at process start (set in TUI autostart).

 */
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { DEFAULT_LOCAL_DEV_API_KEY, GatewayClient, preferIpv4LoopbackGatewayUrl, } from './gateway-client.js';
import { errorMessage } from './tui-handlers-errors.js';
const DEFAULT_LOCAL_DATABASE_URL = 'postgresql://4runr:4runr_dev_pass@localhost:5432/4runr_local';
function isLoopbackGatewayUrl(url) {
    try {
        const h = new URL(url).hostname.toLowerCase();
        return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '0.0.0.0';
    }
    catch {
        return false;
    }
}
function authProbeFailed(msg) {
    return (msg.includes('401') ||
        msg.includes('403') ||
        msg.includes('authentication failed') ||
        msg.includes('unauthorized') ||
        msg.includes('Invalid API key') ||
        msg.includes('Missing x-api-key'));
}
function seedScriptPath() {
    const here = path.dirname(fileURLToPath(import.meta.url));
    return path.join(here, '..', 'scripts', 'seed-gateway-api-key.cjs');
}
function runPostgresSeed(gatewayBundlePath) {
    const script = seedScriptPath();
    if (!fs.existsSync(script)) {
        return { ok: false, detail: `Seed script missing: ${script}` };
    }
    const sh = process.platform === 'win32' ? process.env['COMSPEC'] || 'cmd.exe' : undefined;
    const databaseUrl = process.env.DATABASE_URL || DEFAULT_LOCAL_DATABASE_URL;
    try {
        const out = execSync(`"${process.execPath}" "${script}" "${gatewayBundlePath}" "${DEFAULT_LOCAL_DEV_API_KEY}" "4Runr OS dev"`, {
            cwd: path.dirname(script),
            stdio: 'pipe',
            timeout: 90000,
            windowsHide: true,
            env: { ...process.env, DATABASE_URL: databaseUrl },
            ...(sh ? { shell: sh } : {}),
        });
        const detail = out.toString().trim() || 'seeded';
        return { ok: true, detail };
    }
    catch (e) {
        const err = e;
        const stderr = err.stderr?.toString().trim() ?? '';
        const stdout = err.stdout?.toString().trim() ?? '';
        const detail = stderr || stdout || err.message || 'unknown seed error';
        return { ok: false, detail };
    }
}
async function probeAuth(gatewayUrl) {
    const client = new GatewayClient({ gatewayUrl });
    try {
        await client.getJson('/api/runs?limit=1');
        return { ok: true };
    }
    catch (e) {
        return { ok: false, error: errorMessage(e) };
    }
}
/**

 * Probe /api/runs auth; seed Postgres key or report memory-mode restart hint.

 */
export async function ensureLocalGatewayApiKeySeeded(gatewayUrl, gatewayBundlePath) {
    if (!isLoopbackGatewayUrl(gatewayUrl)) {
        return { ok: true, seeded: false };
    }
    const url = preferIpv4LoopbackGatewayUrl(gatewayUrl);
    const first = await probeAuth(url);
    if (first.ok) {
        return { ok: true, seeded: false };
    }
    const probeMsg = first.error ?? '';
    if (!authProbeFailed(probeMsg)) {
        return { ok: false, seeded: false, hint: probeMsg };
    }
    const bundlePath = gatewayBundlePath?.trim();
    const packageJson = bundlePath ? path.join(bundlePath, 'package.json') : '';
    if (!bundlePath || !fs.existsSync(packageJson)) {
        return {
            ok: false,
            seeded: false,
            hint: 'Gateway API key missing. Disconnect (stops local Gateway), reconnect, or set API_KEY on the Gateway process.',
        };
    }
    const seed = runPostgresSeed(bundlePath);
    if (seed.ok) {
        const retry = await probeAuth(url);
        if (retry.ok) {
            return { ok: true, seeded: true };
        }
    }
    // Postgres seed failed or gateway is in memory mode (API_KEY only read at startup).
    return {
        ok: false,
        seeded: false,
        hint: seed.ok === false
            ? `API key seed failed (${seed.detail}). If Gateway runs in memory mode: disconnect and reconnect so it restarts with API_KEY.`
            : 'Gateway rejected the dev API key. Disconnect and reconnect to restart the local Gateway with API_KEY set.',
    };
}
/** Placeholder so Shield health is operational in local dev (rewrite calls won't succeed against OpenAI). */
const DEFAULT_LOCAL_DEV_OPENAI_API_KEY = 'sk-4runr-local-dev-placeholder';
/** Env vars every OS-spawned local Gateway should inherit for dev auth. */
export function localGatewayDevAuthEnv() {
    return {
        API_KEY: process.env.API_KEY || process.env.GATEWAY_API_KEY || DEFAULT_LOCAL_DEV_API_KEY,
        OPENAI_API_KEY: process.env.OPENAI_API_KEY || DEFAULT_LOCAL_DEV_OPENAI_API_KEY,
    };
}
//# sourceMappingURL=gateway-api-key-bootstrap.js.map