import { runReqOutboundStage3CompatWithNative } from '../../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
import { buildGlmRequestCompatInput } from './glm-native-compat.js';
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
function normalizeImagePart(part) {
    const rawType = typeof part.type === 'string' ? part.type.toLowerCase() : '';
    if (rawType !== 'image' && rawType !== 'image_url') {
        return null;
    }
    // Try multiple locations for the URL, since different inbound
    // protocols may populate different keys.
    const imageUrlBlock = isRecord(part.image_url)
        ? part.image_url
        : undefined;
    let url;
    if (imageUrlBlock && typeof imageUrlBlock.url === 'string') {
        url = imageUrlBlock.url;
    }
    else if (typeof part.image_url === 'string') {
        url = part.image_url;
    }
    else if (typeof part.url === 'string') {
        url = part.url;
    }
    else if (typeof part.uri === 'string') {
        url = part.uri;
    }
    else if (typeof part.data === 'string') {
        // If caller passed a raw base64/data URI string, forward as-is.
        url = part.data;
    }
    if (!url || !url.trim().length) {
        return null;
    }
    const normalized = {
        type: 'image_url',
        image_url: {
            url: url.trim()
        }
    };
    // Preserve a best-effort "detail" field when present.
    const detailValue = (imageUrlBlock && imageUrlBlock.detail) ?? part.detail;
    if (typeof detailValue === 'string' && detailValue.trim().length) {
        normalized.image_url.detail = detailValue.trim();
    }
    return normalized;
}
export function applyGlmImageContentTransform(payload) {
    const root = structuredClone(payload);
    const messagesValue = root.messages;
    if (!Array.isArray(messagesValue)) {
        return root;
    }
    return runReqOutboundStage3CompatWithNative(buildGlmRequestCompatInput(payload)).payload;
}
