import { ShortcutXLProviderUsageStatus } from '../contracts/model-call.js';
import { aiContentToShortcutProxyContent } from './ai-content.js';
function toStructuredCloneSafe(value, seen = new WeakSet()) {
    if (value === null ||
        typeof value === 'string' ||
        typeof value === 'number' ||
        typeof value === 'boolean') {
        return value;
    }
    if (typeof value === 'bigint')
        return value;
    if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {
        return undefined;
    }
    if (Array.isArray(value)) {
        return value
            .map((entry) => toStructuredCloneSafe(entry, seen))
            .filter((entry) => entry !== undefined);
    }
    if (typeof value !== 'object')
        return undefined;
    if (seen.has(value))
        return undefined;
    seen.add(value);
    const output = {};
    for (const [key, entry] of Object.entries(value)) {
        const safeEntry = toStructuredCloneSafe(entry, seen);
        if (safeEntry !== undefined)
            output[key] = safeEntry;
    }
    seen.delete(value);
    return output;
}
function createFallbackModel(input) {
    return {
        api: 'shortcut-llm',
        baseUrl: '',
        contextWindow: 200000,
        cost: { cacheRead: 0, cacheWrite: 0, input: 0, output: 0 },
        id: input.model,
        input: ['text', 'image'],
        maxTokens: input.maxTokens ?? 64000,
        name: input.model,
        provider: 'shortcut',
        reasoning: false
    };
}
function createInvokeModel(input, baseModel) {
    const model = baseModel ?? createFallbackModel(input);
    return {
        ...model,
        id: input.model,
        maxTokens: input.maxTokens ?? model.maxTokens,
        name: input.model,
        reasoning: input.thinkingType === 'on' || input.effortLevel !== undefined || model.reasoning
    };
}
export function createShortcutXLAiModelInvokeRequestFromParams(options) {
    const { params } = options;
    return toStructuredCloneSafe({
        context: {
            ...(params.systemPrompt ? { systemPrompt: params.systemPrompt } : {}),
            messages: [...params.messages],
            ...(params.tools ? { tools: params.tools } : {})
        },
        model: createInvokeModel({
            effortLevel: params.effort_level,
            maxTokens: params.max_tokens,
            model: params.model,
            thinkingType: params.thinking_type,
            toolChoice: params.tool_choice
        }, options.baseModel),
        options: {
            ...(params.effort_level ? { reasoning: params.effort_level } : {}),
            ...(params.max_tokens !== undefined ? { maxTokens: params.max_tokens } : {}),
            ...(options.requestType ? { requestType: options.requestType } : {}),
            ...(params.thinking_type ? { thinkingType: params.thinking_type } : {}),
            ...(params.tool_choice ? { toolChoice: params.tool_choice } : {}),
            ...(options.userMessageId ? { userMessageId: options.userMessageId } : {})
        },
        requestId: options.requestId
    });
}
function toolCallToShortcutProxyToolCall(toolCall) {
    return {
        arguments: JSON.stringify(toolCall.arguments ?? {}),
        id: toolCall.id,
        name: toolCall.name
    };
}
export function shortcutXLAiModelInvokeRequestToPayload(request) {
    const messages = [
        ...(request.context.systemPrompt
            ? [{ content: request.context.systemPrompt, role: 'system' }]
            : [])
    ];
    for (const message of request.context.messages) {
        if (message.role === 'user') {
            messages.push({
                content: aiContentToShortcutProxyContent(message.content, request.model.id),
                role: 'human'
            });
            continue;
        }
        if (message.role === 'assistant') {
            const content = typeof message.content === 'string'
                ? message.content
                : message.content
                    .filter((block) => block.type === 'text')
                    .map((block) => block.text)
                    .join('');
            const toolCalls = typeof message.content === 'string'
                ? undefined
                : message.content
                    .filter((block) => block.type === 'toolCall')
                    .map(toolCallToShortcutProxyToolCall);
            messages.push({
                content,
                role: 'ai',
                ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {})
            });
            continue;
        }
        if (message.role === 'toolResult') {
            messages.push({
                content: aiContentToShortcutProxyContent(message.content, request.model.id),
                role: 'tool',
                toolCallId: message.toolCallId
            });
        }
    }
    return {
        effortLevel: request.options?.reasoning === 'low' ||
            request.options?.reasoning === 'medium' ||
            request.options?.reasoning === 'high'
            ? request.options.reasoning
            : undefined,
        maxTokens: request.options?.maxTokens,
        messages,
        model: request.model.id,
        thinkingType: request.options?.thinkingType,
        toolChoice: typeof request.options?.toolChoice === 'object' ? request.options.toolChoice : undefined,
        tools: request.context.tools?.map((tool) => ({
            description: tool.description,
            name: tool.name,
            parameters: tool.parameters
        }))
    };
}
export function assistantMessageToShortcutXLInvokeResponse(message) {
    if (!message) {
        return { usageStatus: ShortcutXLProviderUsageStatus.Unavailable };
    }
    const text = message.content
        .filter((block) => block.type === 'text')
        .map((block) => block.text)
        .join('');
    const toolCalls = message.content
        .filter((block) => block.type === 'toolCall')
        .map((block) => ({
        arguments: JSON.stringify(block.arguments ?? {}),
        id: block.id,
        name: block.name
    }));
    return {
        stopReason: message.stopReason,
        text: text || undefined,
        toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
        usageStatus: message.usage.totalTokens > 0
            ? ShortcutXLProviderUsageStatus.UsageAvailable
            : ShortcutXLProviderUsageStatus.Unavailable
    };
}
//# sourceMappingURL=ai-invoke.js.map