import { YagrConfigService } from '../config/yagr-config-service.js';
import { runInteractiveGateway } from './interactive-ui.js';
import { resolveLanguageModelConfig, resolveModelProvider } from '../llm/create-language-model.js';
async function ensureProvider(options) {
    const configService = new YagrConfigService();
    const savedConfig = configService.getLocalConfig();
    if (options.provider) {
        return options.provider;
    }
    try {
        return resolveModelProvider(savedConfig.provider, configService);
    }
    catch {
        throw new Error('No LLM provider configured. Run `yagr setup` first.');
    }
}
export async function runCliGateway(agent, options = {}) {
    const configService = new YagrConfigService();
    const savedConfig = configService.getLocalConfig();
    const provider = await ensureProvider({
        ...options,
        provider: options.provider ?? savedConfig.provider,
    });
    const resolvedConfig = resolveLanguageModelConfig({
        provider,
        model: options.model,
        apiKey: options.apiKey,
        baseUrl: options.baseUrl,
    }, configService);
    const effectiveOptions = {
        ...options,
        provider: resolvedConfig.provider,
        model: resolvedConfig.model,
        apiKey: resolvedConfig.apiKey,
        baseUrl: resolvedConfig.baseUrl,
    };
    configService.saveLocalConfig({
        ...savedConfig,
        provider,
        model: effectiveOptions.model,
        baseUrl: effectiveOptions.baseUrl,
    });
    if (options.prompt && !options.interactive) {
        const result = await agent.run(options.prompt, effectiveOptions);
        process.stdout.write(`${result.text}\n`);
        return;
    }
    await runInteractiveGateway(agent, effectiveOptions);
}
//# sourceMappingURL=cli.js.map