const MODEL_MAP = {
    'gpt-3.5-turbo': 'qwen-turbo',
    'gpt-4': 'qwen3-coder-plus',
    'gpt-4-turbo': 'qwen3-coder-plus',
    'gpt-4o': 'qwen3-coder-plus'
};
const FINISH_REASON_MAP = {
    stop: 'stop',
    length: 'length',
    tool_calls: 'tool_calls',
    content_filter: 'content_filter'
};
const isRecord = (value) => typeof value === 'object' && value !== null;
const readReasoningEffort = (value) => {
    if (typeof value === 'string') {
        return value;
    }
    if (isRecord(value) && typeof value.effort === 'string') {
        return value.effort;
    }
    return undefined;
};
export function applyQwenRequestTransform(payload) {
    const cloned = structuredClone(payload);
    const transformed = convertToQwenRequest(cloned);
    return transformed;
}
export function applyQwenResponseTransform(payload) {
    const cloned = structuredClone(payload);
    const transformed = transformQwenResponseToOpenAI(cloned);
    return transformed;
}
function convertToQwenRequest(request) {
    const qwenRequest = {};
    const mappedModel = mapModelName(typeof request.model === 'string' ? request.model : undefined);
    if (mappedModel) {
        qwenRequest.model = mappedModel;
    }
    if (Array.isArray(request.messages)) {
        qwenRequest.messages = structuredClone(request.messages);
        const normalizedMessages = request.messages
            .map(message => normalizeMessage(message))
            .filter((entry) => entry !== null);
        if (normalizedMessages.length > 0) {
            qwenRequest.input = normalizedMessages;
        }
    }
    const parameters = extractParameters(request);
    if (Object.keys(parameters).length > 0) {
        qwenRequest.parameters = parameters;
    }
    if (typeof request.stream === 'boolean') {
        qwenRequest.stream = request.stream;
    }
    if (isRecord(request.response_format)) {
        qwenRequest.response_format = structuredClone(request.response_format);
    }
    if (typeof request.user === 'string') {
        qwenRequest.user = request.user;
    }
    if (Array.isArray(request.tools)) {
        qwenRequest.tools = sanitizeTools(request.tools);
    }
    if (isRecord(request.metadata)) {
        qwenRequest.metadata = structuredClone(request.metadata);
    }
    return qwenRequest;
}
function sanitizeTools(tools) {
    return tools.map(tool => {
        if (!isRecord(tool)) {
            return tool;
        }
        const normalized = {};
        if (typeof tool.type === 'string') {
            normalized.type = tool.type;
        }
        if (isRecord(tool.function)) {
            normalized.function = structuredClone(tool.function);
        }
        return Object.keys(normalized).length > 0 ? normalized : tool;
    });
}
function normalizeMessage(message) {
    if (!isRecord(message)) {
        return null;
    }
    const role = typeof message.role === 'string' ? message.role : 'user';
    const content = normalizeMessageContent(message.content);
    return { role, content };
}
function normalizeMessageContent(content) {
    if (content === undefined || content === null) {
        return [{ text: '' }];
    }
    if (typeof content === 'string') {
        return [{ text: content }];
    }
    if (Array.isArray(content)) {
        return content.map(chunk => normalizeContentChunk(chunk));
    }
    if (isRecord(content) && typeof content.text === 'string') {
        return [{ text: content.text }];
    }
    return [{ text: JSON.stringify(content) }];
}
function normalizeContentChunk(chunk) {
    if (typeof chunk === 'string') {
        return { text: chunk };
    }
    if (isRecord(chunk)) {
        if (typeof chunk.text === 'string') {
            return { text: chunk.text };
        }
        return structuredClone(chunk);
    }
    return { text: String(chunk) };
}
function extractParameters(request) {
    const parameters = {};
    const numericFields = [
        { key: 'temperature', target: 'temperature' },
        { key: 'top_p', target: 'top_p' },
        { key: 'frequency_penalty', target: 'frequency_penalty' },
        { key: 'presence_penalty', target: 'presence_penalty' },
        { key: 'max_tokens', target: 'max_output_tokens' }
    ];
    for (const field of numericFields) {
        const value = request[field.key];
        if (typeof value === 'number') {
            parameters[field.target] = value;
        }
    }
    if (request.stop !== undefined) {
        const stops = Array.isArray(request.stop) ? request.stop : [request.stop];
        const sequences = stops.filter(item => typeof item === 'string');
        if (sequences.length > 0) {
            parameters.stop_sequences = sequences;
        }
    }
    if (typeof request.debug === 'boolean') {
        parameters.debug = request.debug;
    }
    const reasoningEffort = readReasoningEffort(request.reasoning)?.toLowerCase();
    if (reasoningEffort !== 'low') {
        parameters.reasoning = true;
    }
    return parameters;
}
function transformQwenResponseToOpenAI(response) {
    const data = isRecord(response.data) ? response.data : response;
    const usage = isRecord(data.usage)
        ? structuredClone(data.usage)
        : {
            prompt_tokens: 0,
            completion_tokens: 0,
            total_tokens: 0
        };
    const transformed = {
        id: typeof data.id === 'string' ? data.id : `chatcmpl-${Date.now()}`,
        object: 'chat.completion',
        created: typeof data.created === 'number' ? data.created : Math.floor(Date.now() / 1000),
        model: typeof data.model === 'string' ? data.model : 'qwen-turbo',
        choices: transformChoices(data.choices),
        usage,
        _transformed: true,
        _originalFormat: 'qwen',
        _targetFormat: 'openai'
    };
    const firstMessage = (() => {
        const choices = Array.isArray(transformed.choices) ? transformed.choices : [];
        const primary = choices[0] && isRecord(choices[0]) ? choices[0] : undefined;
        const message = primary && isRecord(primary.message) ? primary.message : undefined;
        return message;
    })();
    if (firstMessage && typeof firstMessage.reasoning_content === 'string' && firstMessage.reasoning_content.trim()) {
        transformed.__responses_reasoning = {
            content: [{ type: 'reasoning_text', text: String(firstMessage.reasoning_content).trim() }]
        };
    }
    return transformed;
}
function transformChoices(rawChoices) {
    if (!Array.isArray(rawChoices)) {
        return [];
    }
    return rawChoices.map((choice, index) => {
        const choiceObj = isRecord(choice) ? choice : {};
        const messageObj = isRecord(choiceObj.message) ? choiceObj.message : {};
        const contentDetails = extractContentAndReasoning(messageObj.content);
        const reasoningText = mergeReasoningText(contentDetails?.reasoningText, readString(messageObj.reasoning_content) ?? readString(messageObj.reasoning));
        return {
            index: typeof choiceObj.index === 'number' ? choiceObj.index : index,
            message: {
                role: typeof messageObj.role === 'string' ? messageObj.role : 'assistant',
                content: contentDetails?.contentText ?? (typeof messageObj.content === 'string' ? messageObj.content : ''),
                tool_calls: transformToolCalls(messageObj.tool_calls),
                ...(reasoningText ? { reasoning_content: reasoningText } : {})
            },
            finish_reason: transformFinishReason(typeof choiceObj.finish_reason === 'string' ? choiceObj.finish_reason : undefined)
        };
    });
}
function readString(value) {
    if (typeof value !== 'string') {
        return undefined;
    }
    const trimmed = value.trim();
    return trimmed.length ? trimmed : undefined;
}
function mergeReasoningText(primary, secondary) {
    const parts = [primary, secondary].filter((item) => typeof item === 'string' && item.trim().length > 0);
    if (parts.length === 0) {
        return undefined;
    }
    return parts.join('\n');
}
function extractContentAndReasoning(content) {
    if (!Array.isArray(content)) {
        return null;
    }
    const contentParts = [];
    const reasoningParts = [];
    for (const chunk of content) {
        if (typeof chunk === 'string') {
            contentParts.push(chunk);
            continue;
        }
        if (!isRecord(chunk)) {
            continue;
        }
        const text = readString(chunk.text);
        const type = typeof chunk.type === 'string' ? chunk.type.toLowerCase() : '';
        const isThinking = Boolean(chunk.thought) || type === 'thinking' || type === 'reasoning';
        if (text) {
            if (isThinking) {
                reasoningParts.push(text);
            }
            else {
                contentParts.push(text);
            }
        }
    }
    return {
        contentText: contentParts.join('\n'),
        reasoningText: reasoningParts.length ? reasoningParts.join('\n') : undefined
    };
}
function transformToolCalls(toolCalls) {
    if (!Array.isArray(toolCalls)) {
        return [];
    }
    return toolCalls.map((toolCall, index) => {
        const toolCallObj = isRecord(toolCall) ? toolCall : {};
        const fnObj = isRecord(toolCallObj.function) ? toolCallObj.function : {};
        const id = typeof toolCallObj.id === 'string'
            ? toolCallObj.id
            : `call_${Date.now()}_${index}`;
        const name = typeof fnObj.name === 'string' ? fnObj.name : '';
        const args = typeof fnObj.arguments === 'string'
            ? fnObj.arguments
            : JSON.stringify(fnObj.arguments ?? {});
        return {
            id,
            type: 'function',
            function: { name, arguments: args }
        };
    });
}
function transformFinishReason(reason) {
    if (!reason) {
        return 'stop';
    }
    return FINISH_REASON_MAP[reason] ?? reason;
}
function mapModelName(model) {
    if (!model) {
        return undefined;
    }
    return MODEL_MAP[model] ?? model;
}
