/*
 * 文件定位：Agent 模型适配层 / Provider 接入层 / Provider Carrier。
 * 核心目的：把 provider、endpoint、model、credentialRef、scope 和缓存意图整理成可路由对象。
 * 能力要求1：支持 OpenAI、Anthropic、DeepMind 和 custom provider 的统一 carrier 形状。
 * 能力要求2：把 cachePolicy 作为经济控制预留接口，但第一期不执行缓存策略。
 * 能力要求3：carrier 只引用 credentialRef，不保存 raw credential。
 * 边界：不解析 auth、不发送请求、不做 PromptPack 映射。
 * 对接：被 providerCarrierRegistry、providerProbe、runtime.modelAdapter registry 和 actualInvocationLayer binding 使用。
 * 实现提示：保持显式输入和 public-safe 输出，让上层 harness 能稳定编码使用。
 */
import { isDeepSeekV4Model } from "./modelMetadataRegistry.js";
function hasText(value) {
    return typeof value === "string" && value.trim().length > 0;
}
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
export function createProviderCarrier(input = {}) {
    if (!hasText(input.carrierId)) {
        return {
            ok: false,
            error: { code: "MISSING_CARRIER_ID", message: "providerCarrier requires a carrierId", boundary: "input", publicSafe: true },
            events: ["agentCore.modelAdapter.providerAccess.providerCarrier.rejected"],
        };
    }
    if (!hasText(input.provider)) {
        return {
            ok: false,
            error: { code: "MISSING_PROVIDER", message: "providerCarrier requires a provider", boundary: "input", publicSafe: true },
            events: ["agentCore.modelAdapter.providerAccess.providerCarrier.rejected"],
        };
    }
    if (!hasText(input.endpointShape)) {
        return {
            ok: false,
            error: {
                code: "MISSING_ENDPOINT_SHAPE",
                message: "providerCarrier requires an endpointShape",
                boundary: "input",
                publicSafe: true,
            },
            events: ["agentCore.modelAdapter.providerAccess.providerCarrier.rejected"],
        };
    }
    const reasoning = input.reasoning === undefined
        ? undefined
        : {
            effort: input.reasoning.effort?.trim() || undefined,
            summary: input.reasoning.summary?.trim() || undefined,
        };
    return {
        ok: true,
        carrier: {
            carrierId: input.carrierId.trim(),
            provider: input.provider.trim(),
            endpointShape: input.endpointShape.trim(),
            baseURL: input.baseURL?.trim().replace(/\/+$/u, "") || undefined,
            model: input.model?.trim() || undefined,
            reasoning,
            credentialRef: input.credentialRef,
            scopes: cleanList(input.scopes),
            capabilities: cleanList(input.capabilities),
            cachePolicy: input.cachePolicy ?? { intent: "none" },
            metadata: input.metadata ?? {},
            publicSafe: true,
        },
        events: ["agentCore.modelAdapter.providerAccess.providerCarrier.created"],
    };
}
export const OPENAI_DEFAULT_RESPONSES_BASE_URL = "https://api.openai.com";
export const OPENAI_DEFAULT_CHAT_COMPLETIONS_BASE_URL = "https://api.openai.com";
export const ANTHROPIC_DEFAULT_MESSAGES_BASE_URL = "https://api.anthropic.com";
export const CHATGPT_CODEX_DEFAULT_BASE_URL = "https://chatgpt.com/backend-api/codex";
export function createChatGPTCodexResponsesCarrier(input) {
    return createProviderCarrier({
        ...input,
        provider: "openai",
        endpointShape: "responses",
        baseURL: input.baseURL ?? CHATGPT_CODEX_DEFAULT_BASE_URL,
        credentialRef: input.credentialRef,
        scopes: input.scopes ?? ["model.invoke", "chatgpt.codex.responses"],
        capabilities: input.capabilities ?? ["text", "reasoning", "tool-call", "chatgpt-subscription"],
        metadata: {
            ...(input.metadata ?? {}),
            productChannel: "chatgpt-codex",
            codexAuthStyle: "Authorization+ChatGPT-Account-ID",
            ...(input.clientName ? { clientName: input.clientName } : {}),
            ...(input.clientVersion ? { clientVersion: input.clientVersion } : {}),
        },
    });
}
export function createOpenAIV1ResponsesCarrier(input) {
    return createProviderCarrier({
        ...input,
        provider: "openai",
        endpointShape: "responses",
        baseURL: input.baseURL ?? OPENAI_DEFAULT_RESPONSES_BASE_URL,
        credentialRef: input.credentialRef,
        scopes: input.scopes ?? ["model.invoke", "openai.responses"],
        capabilities: input.capabilities ?? ["text", "reasoning", "tool-call", "streaming"],
        metadata: {
            apiVersion: "v1",
            providerRoute: "openai_responses",
            ...(input.metadata ?? {}),
        },
    });
}
export function createOpenAIV1ChatCompletionsCarrier(input) {
    return createProviderCarrier({
        ...input,
        provider: "openai",
        endpointShape: "chat_completions",
        baseURL: input.baseURL ?? OPENAI_DEFAULT_CHAT_COMPLETIONS_BASE_URL,
        credentialRef: input.credentialRef,
        scopes: input.scopes ?? ["model.invoke", "openai.chat_completions"],
        capabilities: input.capabilities ?? [
            "text",
            ...(isDeepSeekV4Model(input.model) ? ["reasoning"] : []),
            "tool-call",
            "streaming",
        ],
        metadata: {
            apiVersion: "v1",
            providerRoute: "openai_chat_completions",
            ...(input.metadata ?? {}),
        },
    });
}
export function createAnthropicV1MessagesCarrier(input) {
    const apiVersion = input.apiVersion?.trim() || "2023-06-01";
    return createProviderCarrier({
        ...input,
        provider: "anthropic",
        endpointShape: "messages",
        baseURL: input.baseURL ?? ANTHROPIC_DEFAULT_MESSAGES_BASE_URL,
        credentialRef: input.credentialRef,
        scopes: input.scopes ?? ["model.invoke", "anthropic.messages"],
        capabilities: input.capabilities ?? ["text", "reasoning", "tool-call", "streaming"],
        metadata: {
            apiVersion,
            providerRoute: "anthropic_messages",
            ...(input.metadata ?? {}),
        },
    });
}
