/**
 * Anthropic adapter. Uses the `/v1/models` listing endpoint with `x-api-key`
 * and the required `anthropic-version` header. Hostname is fixed.
 */
import { AdapterHttpError, extractModelIds, messageFromStatus, statusFromHttp, timedFetch, } from './http.js';
const ANTHROPIC_BASE = 'https://api.anthropic.com/v1';
const ANTHROPIC_VERSION = '2023-06-01';
function anthropicNum(value) {
    return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
}
function headers(ctx) {
    return { 'x-api-key': ctx.apiKey, 'anthropic-version': ANTHROPIC_VERSION };
}
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(`${ANTHROPIC_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(`${ANTHROPIC_BASE}/models`, { method: 'GET', headers: headers(ctx) }, ctx);
    if (!res.ok)
        throw new Error(`Anthropic model listing failed (${res.status})`);
    return extractModelIds(await res.json());
}
export async function generateText(ctx, opts) {
    const res = await timedFetch(`${ANTHROPIC_BASE}/messages`, {
        method: 'POST',
        headers: { ...headers(ctx), 'content-type': 'application/json' },
        body: JSON.stringify({
            model: opts.model,
            max_tokens: opts.maxTokens ?? 1024,
            ...(opts.system ? { system: opts.system } : {}),
            ...(typeof opts.temperature === 'number' ? { temperature: opts.temperature } : {}),
            messages: [{ role: 'user', content: opts.prompt }],
        }),
    }, ctx);
    if (!res.ok)
        throw new AdapterHttpError(statusFromHttp(res.status), res.status);
    const payload = (await res.json());
    const block = payload.content?.find((b) => b.type === 'text') ?? payload.content?.[0];
    const promptTokens = anthropicNum(payload.usage?.input_tokens);
    const completionTokens = anthropicNum(payload.usage?.output_tokens);
    return {
        text: typeof block?.text === 'string' ? block.text : '',
        usage: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
        model: opts.model,
    };
}
//# sourceMappingURL=anthropic.js.map