import { AuthError, FatalError, QuotaExhaustedError, RateLimitError, TransientError } from "./index.js";
//#region src/anthropic.ts
function extractAnthropicSystem(messages) {
	const systemParts = messages.filter((m) => m.role === "system").map((m) => typeof m.content === "string" ? m.content : m.content.filter((b) => b.type === "text").map((b) => b.text).join(""));
	return systemParts.length > 0 ? systemParts.join("\n\n") : void 0;
}
function mapMessagesToAnthropic(messages) {
	return messages.filter((m) => m.role !== "system").map((message) => ({
		role: message.role === "assistant" ? "assistant" : "user",
		content: mapContentToAnthropic(message.content)
	}));
}
function mapContentToAnthropic(content) {
	if (typeof content === "string") return content;
	return content.map((block) => {
		if (block.type === "text") return {
			type: "text",
			text: block.text
		};
		const img = block.image;
		return {
			type: "image",
			source: {
				type: "base64",
				media_type: img.mediaType,
				data: img.data
			}
		};
	});
}
function mapAnthropicResponse(body, provider, model) {
	return {
		content: body.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join(""),
		model: body.model || model,
		provider,
		usage: {
			promptTokens: body.usage.input_tokens,
			completionTokens: body.usage.output_tokens
		},
		finishReason: body.stop_reason ?? void 0
	};
}
function classifyAnthropicError(status, message, provider) {
	if (status === 429) {
		if (/quota/i.test(message)) return new QuotaExhaustedError(message, provider);
		return new RateLimitError(message, provider);
	}
	if (status === 401 || status === 403) return new AuthError(message, provider);
	if (status >= 500) return new TransientError(message, provider);
	return new FatalError(message, provider);
}
function makeAnthropicAdapter(creds) {
	const baseUrl = creds.baseUrl ?? "https://api.anthropic.com/v1";
	const fetchImpl = creds.fetch ?? fetch;
	return {
		provider: "anthropic",
		supportsImage: true,
		async call(req) {
			const system = extractAnthropicSystem(req.messages);
			const payload = {
				model: req.model,
				max_tokens: req.maxTokens ?? 1024,
				messages: mapMessagesToAnthropic(req.messages),
				...system ? { system } : {},
				...req.temperature !== void 0 ? { temperature: req.temperature } : {},
				...req.stop !== void 0 ? { stop_sequences: Array.isArray(req.stop) ? req.stop : [req.stop] } : {}
			};
			const response = await fetchImpl(`${baseUrl}/messages`, {
				method: "POST",
				headers: {
					"x-api-key": creds.apiKey,
					"anthropic-version": "2023-06-01",
					"Content-Type": "application/json"
				},
				body: JSON.stringify(payload)
			});
			const text = await response.text();
			let body;
			try {
				body = JSON.parse(text);
			} catch {
				throw new TransientError(`Invalid JSON from provider: ${text.slice(0, 120)}`, "anthropic");
			}
			if (!response.ok) {
				const message = typeof body === "object" && body !== null && "error" in body && typeof body.error?.message === "string" ? body.error.message : text;
				throw classifyAnthropicError(response.status, message, "anthropic");
			}
			return mapAnthropicResponse(body, "anthropic", req.model);
		}
	};
}
//#endregion
export { classifyAnthropicError, extractAnthropicSystem, makeAnthropicAdapter, mapAnthropicResponse, mapContentToAnthropic, mapMessagesToAnthropic };
