import { randomUUID } from 'node:crypto';
import { responseModelName } from '../config.js';
function mapStopReason(fr) {
    switch (fr) {
        case 'stop': return 'end_turn';
        case 'tool_calls': return 'tool_use';
        case 'length': return 'max_tokens';
        default: return 'end_turn';
    }
}
export function translateResponse(openaiResp, requestModel, config) {
    const id = `msg_${randomUUID().replace(/-/g, '').slice(0, 24)}`;
    const choice = openaiResp.choices[0];
    const content = [];
    // Moonshot/Kimi OpenAI-compatible responses include reasoning_content for
    // thinking models. Preserve it as Anthropic thinking content so later turns
    // can echo the reasoning history back to Kimi instead of losing it.
    if (choice.message.reasoning_content) {
        content.push({ type: 'thinking', thinking: choice.message.reasoning_content });
    }
    // text → text block
    if (choice.message.content) {
        content.push({ type: 'text', text: choice.message.content });
    }
    // tool_calls → tool_use blocks
    if (choice.message.tool_calls) {
        for (const tc of choice.message.tool_calls) {
            let input;
            try {
                input = JSON.parse(tc.function.arguments);
            }
            catch {
                // Malformed JSON from backend — preserve the raw argument string so the
                // compatibility client can still inspect the tool call.
                input = { _raw: tc.function.arguments };
            }
            content.push({
                type: 'tool_use',
                id: tc.id,
                name: tc.function.name,
                input,
            });
        }
    }
    // Empty content fallback
    if (content.length === 0) {
        content.push({ type: 'text', text: '' });
    }
    // OpenAI's prompt_tokens INCLUDES any cached prefix; Anthropic's usage shape
    // keeps input_tokens / cache_read_input_tokens disjoint. Split them so /cost
    // accounting matches the native Anthropic path. Providers that omit
    // prompt_tokens_details report zero cache (feature-detect by absence).
    const promptTokens = openaiResp.usage?.prompt_tokens ?? 0;
    const cachedTokens = openaiResp.usage?.prompt_tokens_details?.cached_tokens ?? 0;
    const usage = {
        input_tokens: Math.max(0, promptTokens - cachedTokens),
        output_tokens: openaiResp.usage?.completion_tokens ?? 0,
        cache_creation_input_tokens: 0,
        cache_read_input_tokens: cachedTokens,
    };
    const model = responseModelName(config, requestModel);
    return {
        id,
        type: 'message',
        role: 'assistant',
        model,
        content,
        stop_reason: mapStopReason(choice.finish_reason),
        stop_sequence: null,
        usage,
    };
}
//# sourceMappingURL=response.js.map