/**
 * OpenAI (and OpenAI-compatible) adapter. Uses the `/v1/models` listing
 * endpoint with Bearer auth. Hostname is fixed (api.openai.com) so no SSRF
 * validation is needed here.
 */
import { extractModelIds, messageFromStatus, openAiChat, statusFromHttp, timedFetch, } from './http.js';
const OPENAI_BASE = 'https://api.openai.com/v1';
function headers(ctx) {
    const h = { authorization: `Bearer ${ctx.apiKey}` };
    if (ctx.organizationId)
        h['openai-organization'] = ctx.organizationId;
    if (ctx.projectId)
        h['openai-project'] = ctx.projectId;
    return h;
}
export async function testConnection(ctx) {
    const testedAt = new Date().toISOString();
    if (!ctx.apiKey) {
        return { ok: false, status: 'needs_setup', message: messageFromStatus('needs_setup'), testedAt };
    }
    try {
        const res = await timedFetch(`${OPENAI_BASE}/models`, { method: 'GET', headers: headers(ctx) }, ctx);
        const status = statusFromHttp(res.status);
        return { ok: status === 'connected', status, message: messageFromStatus(status), testedAt };
    }
    catch {
        return {
            ok: false,
            status: 'provider_down',
            message: messageFromStatus('provider_down'),
            testedAt,
        };
    }
}
export async function listModels(ctx) {
    const res = await timedFetch(`${OPENAI_BASE}/models`, { method: 'GET', headers: headers(ctx) }, ctx);
    if (!res.ok)
        throw new Error(`OpenAI model listing failed (${res.status})`);
    return extractModelIds(await res.json());
}
export function generateText(ctx, opts) {
    return openAiChat(OPENAI_BASE, headers(ctx), ctx, opts);
}
//# sourceMappingURL=openai.js.map