import { isPromptCachingEnabled } from "./caching-config.js";
import { ModelFactory } from "@inkeep/agents-core";

//#region src/domains/run/agents/generation/caching-actuator.ts
function attachPromptCaching(config, modelSettings) {
	if (!isPromptCachingEnabled()) return config;
	if (ModelFactory.shouldRouteViaGateway(modelSettings)) {
		const providerOptions = config.providerOptions ?? {};
		const gateway = providerOptions.gateway ?? {};
		return {
			...config,
			providerOptions: {
				...providerOptions,
				gateway: {
					...gateway,
					caching: gateway.caching ?? "auto"
				}
			}
		};
	}
	if (!config.messages || config.messages.length === 0) return config;
	const modelString = modelSettings.model?.trim();
	if (!modelString) return config;
	const { provider } = ModelFactory.parseModelString(modelString);
	if (provider !== "anthropic") return config;
	return {
		...config,
		messages: config.messages.map((msg) => {
			if (msg.role !== "system") return msg;
			const msgProviderOptions = msg.providerOptions ?? {};
			const anthropic = msgProviderOptions.anthropic ?? {};
			return {
				...msg,
				providerOptions: {
					...msgProviderOptions,
					anthropic: {
						...anthropic,
						cacheControl: anthropic.cacheControl ?? { type: "ephemeral" }
					}
				}
			};
		})
	};
}

//#endregion
export { attachPromptCaching };