/**
 * Ensure the default local dev API key exists in the Gateway DB.
 * Without this, /api/* routes return 401 even though /health works.
 */
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { DEFAULT_LOCAL_DEV_API_KEY, GatewayClient, preferIpv4LoopbackGatewayUrl, } from './gateway-client.js';
import { errorMessage } from './tui-handlers-errors.js';
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'));
}
/**
 * Probe /api/runs auth; seed DEFAULT_LOCAL_DEV_API_KEY when missing on loopback Gateways.
 */
export async function ensureLocalGatewayApiKeySeeded(gatewayUrl, gatewayBundlePath) {
    if (!isLoopbackGatewayUrl(gatewayUrl)) {
        return { ok: true, seeded: false };
    }
    const url = preferIpv4LoopbackGatewayUrl(gatewayUrl);
    const client = new GatewayClient({ gatewayUrl: url });
    try {
        await client.getJson('/api/runs?limit=1');
        return { ok: true, seeded: false };
    }
    catch (e) {
        const msg = errorMessage(e);
        if (!authProbeFailed(msg)) {
            return { ok: false, seeded: false, hint: msg };
        }
    }
    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. From the gateway bundle run: npm run seed:api-key -- test-key-ce67dabb0d4e27e3d72877c921b89cae',
        };
    }
    try {
        const sh = process.platform === 'win32' ? process.env['COMSPEC'] || 'cmd.exe' : undefined;
        execSync(`npm run seed:api-key -- ${DEFAULT_LOCAL_DEV_API_KEY} "4Runr OS dev"`, {
            cwd: bundlePath,
            stdio: 'pipe',
            timeout: 90000,
            windowsHide: true,
            ...(sh ? { shell: sh } : {}),
        });
        const retry = new GatewayClient({ gatewayUrl: url });
        await retry.getJson('/api/runs?limit=1');
        return { ok: true, seeded: true };
    }
    catch (e) {
        return {
            ok: false,
            seeded: false,
            hint: `Could not seed API key: ${errorMessage(e)}`,
        };
    }
}
//# sourceMappingURL=gateway-api-key-bootstrap.js.map