import { Runner, OpenAIProvider } from '@openai/agents';
import { createOpenAIClient, getCurrentOpenAIProvider, getCurrentOpenAIProviderOptions, normalizeBaseUrl } from './chatAgent';
import { streamOpenAIResponse } from './streamResponse';
const resolveOpenAIModelProvider = (options) => {
    const provider = getCurrentOpenAIProvider();
    if (provider) {
        return provider;
    }
    const providerOptions = getCurrentOpenAIProviderOptions();
    if (providerOptions) {
        return new OpenAIProvider(providerOptions);
    }
    const sanitizedApiKey = typeof options.apiKey === 'string' ? options.apiKey.trim() : '';
    const baseUrl = normalizeBaseUrl(options.baseUrl, options.connection);
    if (!sanitizedApiKey) {
        const fallbackProviderOptions = {};
        if (baseUrl) {
            fallbackProviderOptions.baseURL = baseUrl;
        }
        if (options.apiMode) {
            fallbackProviderOptions.useResponses = options.apiMode !== 'chat_completions';
        }
        return new OpenAIProvider(fallbackProviderOptions);
    }
    const client = createOpenAIClient({
        ...options,
        apiKey: sanitizedApiKey,
        ...(baseUrl ? { baseUrl } : {})
    });
    const openAIProviderOptions = {
        openAIClient: client
    };
    if (options.apiMode) {
        openAIProviderOptions.useResponses = options.apiMode !== 'chat_completions';
    }
    return new OpenAIProvider(openAIProviderOptions);
};
const createRunner = (options) => {
    return new Runner({
        modelProvider: resolveOpenAIModelProvider(options)
    });
};
export const runOpenAIChat = async ({ agent, thread, context, signal, handlers, chatOptions }) => {
    const runner = createRunner(chatOptions);
    const response = await runner.run(agent, thread, {
        stream: true,
        context,
        signal
    });
    await streamOpenAIResponse(response, handlers);
    return { response };
};
export const resumeOpenAIChat = async ({ agent, state, context, signal, handlers, chatOptions }) => {
    const runner = createRunner(chatOptions);
    const response = await runner.run(agent, state, {
        stream: true,
        context,
        signal
    });
    await streamOpenAIResponse(response, handlers);
    return { response };
};
export { resolveOpenAIModelProvider };
