import type { Api, Model } from "@earendil-works/pi-ai";
import type { ExplabsModel } from "./types.ts";

export interface ProtocolHints {
	maker?: string;
	defaultProvider?: string;
}

interface ProtocolModel {
	id: string;
	protocolHints?: ProtocolHints;
	nativeOpenAIRoute?: boolean;
}

/** Prefer a model family's native wire format among the gateway's supported chat APIs. */
export function selectChatApi(model: ProtocolModel): ExplabsModel["api"] {
	const maker = model.protocolHints?.maker?.toLowerCase();
	const provider = model.protocolHints?.defaultProvider;
	if (maker === "anthropic" || model.id.startsWith("claude-") || provider === "anthropic") {
		return "anthropic-messages";
	}
	if (/^gpt-oss(?:-|$)/.test(model.id) && !model.nativeOpenAIRoute && provider !== "openai") {
		return "openai-completions";
	}
	if (maker === "openai" || model.nativeOpenAIRoute || provider === "openai" ||
		/^(?:gpt-|chatgpt-|o[1-9](?:-|$))/.test(model.id)) {
		return "openai-responses";
	}
	return "openai-completions";
}

export function selectClassifierApi(hints: ProtocolHints): "openai-decisions" | "typesafe-system-one" {
	return hints.defaultProvider === "openai" ? "openai-decisions" : "typesafe-system-one";
}

export function chatBaseUrl(baseUrl: string, api: ExplabsModel["api"]): string {
	return api === "anthropic-messages" ? baseUrl.replace(/\/v1$/, "") : baseUrl;
}

export function chatCompat(api: ExplabsModel["api"], options: {
	supportsDeveloperRole?: boolean;
	supportsStrictMode?: boolean;
	supportsTemperature?: boolean;
	adaptiveThinking?: boolean;
}, previous?: Model<Api>["compat"]): Model<Api>["compat"] {
	if (api === "anthropic-messages") {
		const compat = { ...previous };
		// Remove the extension's old restriction from cached models as well.
		if ("supportsLongCacheRetention" in compat) delete compat.supportsLongCacheRetention;
		return {
			...compat,
			...(options.supportsTemperature !== undefined ? { supportsTemperature: options.supportsTemperature } : {}),
			...(options.adaptiveThinking ? { forceAdaptiveThinking: true } : {}),
		};
	}
	return {
		...previous,
		supportsDeveloperRole: options.supportsDeveloperRole ?? false,
		supportsStrictMode: options.supportsStrictMode ?? false,
		...(api === "openai-completions" ? {
			// The gateway accepts OpenAI-style reasoning_effort and max_tokens on every chat route.
			thinkingFormat: "openai" as const,
			supportsReasoningEffort: true,
			maxTokensField: "max_tokens" as const,
		} : {}),
	};
}
