"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.createOpenAIEnv = createOpenAIEnv;
exports.loadOpenAIConfig = loadOpenAIConfig;
exports.hasOpenAICredentials = hasOpenAICredentials;
exports.getOpenAIRuntimeDiagnostics = getOpenAIRuntimeDiagnostics;
const outputLanguage_1 = require("../agentv3/outputLanguage");
const providerManager_1 = require("../services/providerManager");
const envIsolation_1 = require("../services/providerManager/envIsolation");
const envCredentialSources_1 = require("../agentRuntime/envCredentialSources");
const config_1 = require("../config");
const DEFAULT_MODEL = 'gpt-5.5';
const DEFAULT_LIGHT_MODEL = 'gpt-5.4-mini';
const DEFAULT_BASE_URL = 'https://api.openai.com/v1';
const DEFAULT_MAX_OUTPUT_TOKENS = 2048;
function parsePositiveIntEnv(env, name, fallback) {
    const value = env[name];
    if (!value)
        return fallback;
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
function parseProtocol(value) {
    return value === 'chat_completions' ? 'chat_completions' : 'responses';
}
function createOpenAIEnv(providerId, providerScope) {
    const svc = (0, providerManager_1.getProviderService)();
    const provider = typeof providerId === 'string'
        ? svc.getRawProvider(providerId, providerScope)
        : providerId === null
            ? undefined
            : svc.getRawEffectiveProvider(providerScope);
    if (typeof providerId === 'string' && !provider) {
        throw new Error(`Provider not found: ${providerId}`);
    }
    const providerRuntime = provider ? svc.resolveAgentRuntime(provider) : undefined;
    if (typeof providerId === 'string' && providerRuntime !== 'openai-agents-sdk') {
        throw new Error(`Provider ${providerId} is configured for ${providerRuntime}, not openai-agents-sdk`);
    }
    const providerEnv = providerRuntime === 'openai-agents-sdk' && provider
        ? svc.getEnvForProvider(provider.id, providerScope)
        : null;
    return (0, envIsolation_1.mergeIsolatedProviderEnv)(process.env, providerEnv);
}
function loadOpenAIConfig(providerId, providerScope) {
    const env = createOpenAIEnv(providerId, providerScope);
    const budgetConfig = (0, config_1.resolveAgentRuntimeBudgetConfig)(env);
    return {
        model: env.OPENAI_MODEL || DEFAULT_MODEL,
        lightModel: env.OPENAI_LIGHT_MODEL || DEFAULT_LIGHT_MODEL,
        maxOutputTokens: parsePositiveIntEnv(env, 'OPENAI_MAX_OUTPUT_TOKENS', DEFAULT_MAX_OUTPUT_TOKENS),
        maxTurns: parsePositiveIntEnv(env, 'OPENAI_MAX_TURNS', parsePositiveIntEnv(env, 'CLAUDE_MAX_TURNS', budgetConfig.maxTurns)),
        quickMaxTurns: parsePositiveIntEnv(env, 'OPENAI_QUICK_MAX_TURNS', parsePositiveIntEnv(env, 'CLAUDE_QUICK_MAX_TURNS', budgetConfig.quickMaxTurns)),
        baseURL: env.OPENAI_BASE_URL || DEFAULT_BASE_URL,
        apiKey: env.OPENAI_API_KEY,
        protocol: parseProtocol(env.OPENAI_AGENTS_PROTOCOL),
        cwd: env.OPENAI_CWD || env.CLAUDE_CWD || process.cwd(),
        fullPathPerTurnMs: parsePositiveIntEnv(env, 'OPENAI_FULL_PER_TURN_MS', parsePositiveIntEnv(env, 'CLAUDE_FULL_PER_TURN_MS', 60000)),
        quickPathPerTurnMs: parsePositiveIntEnv(env, 'OPENAI_QUICK_PER_TURN_MS', parsePositiveIntEnv(env, 'CLAUDE_QUICK_PER_TURN_MS', 40000)),
        classifierTimeoutMs: parsePositiveIntEnv(env, 'OPENAI_CLASSIFIER_TIMEOUT_MS', parsePositiveIntEnv(env, 'CLAUDE_CLASSIFIER_TIMEOUT_MS', 30000)),
        outputLanguage: (0, outputLanguage_1.parseOutputLanguage)(env.SMARTPERFETTO_OUTPUT_LANGUAGE),
    };
}
function hasOpenAICredentials(providerId, providerScope) {
    const env = createOpenAIEnv(providerId, providerScope);
    const baseUrl = env.OPENAI_BASE_URL || '';
    return Boolean((0, envCredentialSources_1.hasConcreteEnvValue)(env.OPENAI_API_KEY)
        || baseUrl.includes('localhost')
        || baseUrl.includes('127.0.0.1')
        || baseUrl.includes('0.0.0.0'));
}
function getOpenAIRuntimeDiagnostics(providerId, providerScope) {
    const env = createOpenAIEnv(providerId, providerScope);
    const config = loadOpenAIConfig(providerId, providerScope);
    const credentialSources = [];
    if ((0, envCredentialSources_1.hasConcreteEnvValue)(env.OPENAI_API_KEY))
        credentialSources.push('openai_api_key');
    if ((0, envCredentialSources_1.hasConcreteEnvValue)(env.OPENAI_BASE_URL))
        credentialSources.push('openai_base_url');
    return {
        runtime: 'openai-agents-sdk',
        providerMode: config.protocol === 'responses'
            ? 'openai_responses'
            : 'openai_chat_completions_compatible',
        model: config.model,
        lightModel: config.lightModel,
        protocol: config.protocol,
        baseUrl: (0, envCredentialSources_1.redactUrlForDiagnostics)(config.baseURL),
        baseUrlConfigured: (0, envCredentialSources_1.hasConcreteEnvValue)(env.OPENAI_BASE_URL),
        configured: hasOpenAICredentials(providerId, providerScope),
        credentialSources,
        maxOutputTokens: config.maxOutputTokens,
        outputLanguage: {
            value: config.outputLanguage,
            displayName: (0, outputLanguage_1.outputLanguageDisplayName)(config.outputLanguage),
            env: 'SMARTPERFETTO_OUTPUT_LANGUAGE',
            default: outputLanguage_1.DEFAULT_OUTPUT_LANGUAGE,
        },
        configHint: config.protocol === 'responses'
            ? 'Using OpenAI Responses API through the OpenAI Agents SDK. Set OPENAI_API_KEY, OPENAI_MODEL, and optionally OPENAI_BASE_URL.'
            : 'Using an OpenAI-compatible Chat Completions endpoint through the OpenAI Agents SDK. Ensure the endpoint supports streaming function/tool calls.',
    };
}
//# sourceMappingURL=openAiConfig.js.map