import { normalizeTelemetryQuery } from './http-helpers.js';
export function assertObjectField(container, field, endpoint) {
    if (container === null
        || typeof container !== 'object'
        || !(field in container)
        || container[field] === null
        || typeof container[field] !== 'object') {
        throw new Error(`[${endpoint}] Expected response to contain object field "${field}"`);
    }
    return container[field];
}
export function assertObjectOrNullField(container, field, endpoint) {
    if (container === null || typeof container !== 'object') {
        throw new Error(`[${endpoint}] Expected response to be an object`);
    }
    const value = container[field];
    if (value === null || value === undefined)
        return null;
    if (typeof value !== 'object') {
        throw new Error(`[${endpoint}] Expected field "${field}" to be an object or null`);
    }
    return value;
}
export function assertArrayField(container, field, endpoint) {
    if (container === null || typeof container !== 'object') {
        throw new Error(`[${endpoint}] Expected response to be an object`);
    }
    const value = container[field];
    if (!Array.isArray(value)) {
        throw new Error(`[${endpoint}] Expected field "${field}" to be an array`);
    }
    return value;
}
export function assertRuntimeTaskArray(tasks, endpoint) {
    if (!Array.isArray(tasks)) {
        throw new Error(`[${endpoint}] Expected "tasks" to be an array`);
    }
    for (const task of tasks) {
        if (task === null || typeof task !== 'object' || typeof task.id !== 'string') {
            throw new Error(`[${endpoint}] Task entry missing required "id" field`);
        }
    }
    return tasks;
}
export function assertSharedApprovalArray(approvals, endpoint) {
    if (!Array.isArray(approvals)) {
        throw new Error(`[${endpoint}] Expected "approvals" to be an array`);
    }
    return approvals;
}
export function assertProviderRuntimeSnapshotArray(providers, endpoint) {
    if (!Array.isArray(providers)) {
        throw new Error(`[${endpoint}] Expected "providers" to be an array`);
    }
    for (const provider of providers) {
        if (provider === null
            || typeof provider !== 'object'
            || typeof provider.providerId !== 'string') {
            throw new Error(`[${endpoint}] Provider entry missing required "providerId" field`);
        }
    }
    return providers;
}
export function assertProviderRuntimeSnapshot(value, endpoint) {
    if (value === null
        || typeof value !== 'object'
        || typeof value.providerId !== 'string') {
        throw new Error(`[${endpoint}] Expected ProviderRuntimeSnapshot with "providerId" field`);
    }
    return value;
}
export function assertProviderUsageSnapshot(value, endpoint) {
    if (value === null
        || typeof value !== 'object'
        || typeof value.providerId !== 'string') {
        throw new Error(`[${endpoint}] Expected ProviderUsageSnapshot with "providerId" field`);
    }
    return value;
}
export function assertTelemetrySnapshot(value, endpoint) {
    if (value === null
        || typeof value !== 'object'
        || value.version !== 1
        || typeof value.generatedAt !== 'number') {
        throw new Error(`[${endpoint}] Expected TelemetrySnapshot with version=1 and numeric "generatedAt"`);
    }
    return value;
}
export function assertTelemetryListResponse(value, endpoint) {
    if (value === null
        || typeof value !== 'object'
        || value.version !== 1
        || !Array.isArray(value.items)) {
        throw new Error(`[${endpoint}] Expected TelemetryListResponse with version=1 and "items" array`);
    }
    return value;
}
export function assertTelemetryMetricsSnapshot(value, endpoint) {
    if (value === null
        || typeof value !== 'object'
        || value.version !== 1
        || typeof value.generatedAt !== 'number') {
        throw new Error(`[${endpoint}] Expected HttpTransportTelemetryMetricsSnapshot with version=1 and numeric "generatedAt"`);
    }
    return value;
}
export function normalizeSharedSessionRecord(record) {
    const candidate = record;
    return {
        ...candidate,
        surfaceKinds: (candidate.surfaceKinds ?? []),
        participants: (candidate.participants ?? []).map((participant) => ({
            ...participant,
            surfaceKind: participant.surfaceKind,
        })),
    };
}
export function normalizeSharedSessionMessage(message, fallbackInput) {
    if (message && typeof message === 'object') {
        const candidate = message;
        return {
            ...candidate,
            surfaceKind: candidate.surfaceKind,
        };
    }
    if (!fallbackInput) {
        throw new Error('Shared session submission did not include a message');
    }
    return {
        id: fallbackInput.causationId ?? `msg-${fallbackInput.id}`,
        sessionId: fallbackInput.sessionId,
        role: 'user',
        body: fallbackInput.body,
        createdAt: fallbackInput.createdAt,
        surfaceKind: fallbackInput.surfaceKind,
        surfaceId: fallbackInput.surfaceId,
        routeId: fallbackInput.routeId,
        userId: fallbackInput.userId,
        displayName: fallbackInput.displayName,
        metadata: fallbackInput.metadata,
    };
}
export function normalizeSharedSessionInput(record) {
    const candidate = record;
    return {
        ...candidate,
        surfaceKind: candidate.surfaceKind,
    };
}
export function normalizeSharedSessionSubmission(record) {
    const sessionValue = record.session;
    if (!sessionValue || typeof sessionValue !== 'object') {
        throw new Error('Shared session submission did not include a session');
    }
    const inputValue = record.input;
    if (!inputValue || typeof inputValue !== 'object') {
        throw new Error('Shared session submission did not include an input');
    }
    const session = normalizeSharedSessionRecord(sessionValue);
    const input = normalizeSharedSessionInput(inputValue);
    return {
        session,
        userMessage: normalizeSharedSessionMessage(record.message ?? record.userMessage, input),
        routeBinding: record.routeBinding,
        input,
        intent: input.intent,
        mode: record.mode,
        state: input.state,
        task: typeof record.task === 'string' ? record.task : undefined,
        activeAgentId: typeof record.agentId === 'string'
            ? record.agentId
            : typeof record.activeAgentId === 'string'
                ? record.activeAgentId
                : undefined,
        created: Boolean(record.created),
    };
}
export function normalizeTelemetryQueryForSdk(query, defaultLimit) {
    const normalized = normalizeTelemetryQuery(query, defaultLimit);
    return {
        ...(normalized.limit !== undefined ? { limit: normalized.limit } : {}),
        ...(normalized.since !== undefined ? { since: normalized.since } : {}),
        ...(normalized.until !== undefined ? { until: normalized.until } : {}),
        ...(normalized.domains?.length ? { domains: normalized.domains.join(',') } : {}),
        ...(normalized.eventTypes?.length ? { types: normalized.eventTypes.join(',') } : {}),
        ...(normalized.severity ? { severity: normalized.severity } : {}),
        ...(normalized.traceId ? { traceId: normalized.traceId } : {}),
        ...(normalized.sessionId ? { sessionId: normalized.sessionId } : {}),
        ...(normalized.turnId ? { turnId: normalized.turnId } : {}),
        ...(normalized.agentId ? { agentId: normalized.agentId } : {}),
        ...(normalized.taskId ? { taskId: normalized.taskId } : {}),
        ...(normalized.cursor ? { cursor: normalized.cursor } : {}),
        ...(normalized.view ? { view: normalized.view } : {}),
    };
}
