"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.runProviderListCommand = runProviderListCommand;
exports.runProviderTestCommand = runProviderTestCommand;
const bootstrap_1 = require("../bootstrap");
const providerManager_1 = require("../../services/providerManager");
const connectionTester_1 = require("../../services/providerManager/connectionTester");
const runtimeSelection_1 = require("../../agentRuntime/runtimeSelection");
const claudeConfig_1 = require("../../agentv3/claudeConfig");
const openAiConfig_1 = require("../../agentOpenAI/openAiConfig");
const stdio_1 = require("../io/stdio");
const runtimeGuard_1 = require("../services/runtimeGuard");
async function runProviderListCommand(args) {
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir, requireLlm: false });
    const format = args.format ?? 'text';
    const providers = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, providerManager_1.getProviderService)().list());
    if (format === 'json' || format === 'ndjson') {
        console.log(JSON.stringify({ ok: true, providers }, null, format === 'json' ? 2 : 0));
        return 0;
    }
    if (providers.length === 0) {
        console.log('(no providers configured; using env/default runtime)');
        return 0;
    }
    for (const p of providers) {
        const active = p.isActive ? '*' : ' ';
        const runtime = (0, providerManager_1.getProviderService)().resolveAgentRuntime((0, providerManager_1.getProviderService)().getRaw(p.id) ?? p);
        console.log(`${active} ${p.id}  ${p.name}  ${p.type}  ${runtime}  model=${p.models.primary}`);
    }
    return 0;
}
async function runProviderTestCommand(args) {
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir, requireLlm: false });
    const format = args.format ?? 'text';
    const target = args.target || 'system';
    const svc = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, providerManager_1.getProviderService)());
    if (target !== 'system') {
        const provider = svc.getRaw(target);
        if (!provider) {
            return writeResult(format, {
                ok: false,
                target,
                error: `provider not found: ${target}`,
            });
        }
        const result = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, connectionTester_1.testProviderConnection)(provider));
        return writeResult(format, {
            ok: result.success,
            target,
            provider: { id: provider.id, name: provider.name, type: provider.type },
            result,
        });
    }
    const selection = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, runtimeSelection_1.resolveAgentRuntimeSelection)());
    const providerId = selection.source === 'provider' ? selection.providerId ?? null : null;
    if (providerId) {
        const provider = svc.getRaw(providerId);
        if (!provider) {
            return writeResult(format, {
                ok: false,
                target: 'system',
                runtime: selection,
                error: `active provider not found: ${providerId}`,
            });
        }
        const result = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, connectionTester_1.testProviderConnection)(provider));
        return writeResult(format, {
            ok: result.success,
            target: 'system',
            runtime: selection,
            provider: { id: provider.id, name: provider.name, type: provider.type },
            result,
            note: result.success
                ? 'Active provider connection test passed.'
                : result.error || 'Active provider connection test failed.',
        });
    }
    if (selection.kind === 'openai-agents-sdk') {
        const diagnostics = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, openAiConfig_1.getOpenAIRuntimeDiagnostics)(providerId));
        return writeResult(format, {
            ok: (0, openAiConfig_1.hasOpenAICredentials)(providerId),
            target: 'system',
            runtime: selection,
            diagnostics,
            note: (0, openAiConfig_1.hasOpenAICredentials)(providerId)
                ? 'OpenAI-compatible runtime is configured.'
                : 'OpenAI-compatible runtime needs OPENAI_API_KEY or a localhost provider endpoint.',
        });
    }
    const diagnostics = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => (0, claudeConfig_1.getClaudeRuntimeDiagnostics)(providerId));
    const binaryOk = (0, runtimeGuard_1.isClaudeSdkBinaryUsable)(diagnostics.sdkBinary);
    return writeResult(format, {
        ok: binaryOk,
        target: 'system',
        runtime: selection,
        diagnostics,
        note: !binaryOk
            ? 'Claude Agent SDK native binary is missing or not executable.'
            : diagnostics.configured
                ? 'Claude runtime has explicit credentials.'
                : 'Claude runtime has no explicit credentials; local Claude login fallback will be used if available.',
    });
}
function writeResult(format, payload) {
    if (format === 'json' || format === 'ndjson') {
        console.log(JSON.stringify(payload, null, format === 'json' ? 2 : 0));
    }
    else if (payload.ok) {
        console.log('OK');
        if (payload.note)
            console.log(String(payload.note));
    }
    else {
        console.error(`Error: ${payload.error || payload.note || 'provider test failed'}`);
    }
    return payload.ok ? 0 : 1;
}
//# sourceMappingURL=provider.js.map