import { estimateTokens } from './context-compaction.js';
export function normalizeUsage(usage) {
    const cacheReadTokens = usage.cacheReadTokens ?? 0;
    const hasExplicitCacheBreakout = Object.prototype.hasOwnProperty.call(usage, 'cacheWriteTokens');
    const freshInputTokens = hasExplicitCacheBreakout
        ? usage.inputTokens
        : Math.max(0, usage.inputTokens - cacheReadTokens);
    return {
        ...usage,
        inputTokens: freshInputTokens,
    };
}
export function estimateFreshTurnInputTokens(lastInputTokens, currentEstimatedTokens, text, content) {
    const explicitContentTokens = content?.reduce((sum, part) => {
        if (part.type === 'text')
            return sum + estimateTextTokens(part.text);
        return sum;
    }, 0) ?? 0;
    const currentTurnPayloadTokens = Math.max(explicitContentTokens, estimateTextTokens(text));
    if (lastInputTokens <= 0) {
        return Math.max(currentEstimatedTokens, currentTurnPayloadTokens);
    }
    const deltaFromPreviousContext = currentEstimatedTokens - lastInputTokens;
    if (deltaFromPreviousContext > 0) {
        return Math.max(deltaFromPreviousContext, currentTurnPayloadTokens);
    }
    if (currentEstimatedTokens < Math.floor(lastInputTokens * 0.8)) {
        return Math.max(currentEstimatedTokens, currentTurnPayloadTokens);
    }
    return currentTurnPayloadTokens;
}
export function getSessionLineageTracker(services, ownedSessionLineageTracker) {
    return services.sessionLineageTracker ?? ownedSessionLineageTracker;
}
export function getIdempotencyStore(services, ownedIdempotencyStore) {
    return services.idempotencyStore ?? ownedIdempotencyStore;
}
export function requireConfigManager(services) {
    if (!services.configManager) {
        throw new Error('Orchestrator requires configManager in core services');
    }
    return services.configManager;
}
export function requireProviderRegistry(services) {
    if (!services.providerRegistry) {
        throw new Error('Orchestrator requires providerRegistry in core services');
    }
    return services.providerRegistry;
}
export function getCacheHitTracker(services, ownedCacheHitTracker) {
    return services.cacheHitTracker ?? ownedCacheHitTracker;
}
export function createEmitterContext(sessionId, turnId) {
    return {
        sessionId,
        traceId: `${sessionId}:${turnId}`,
        source: 'orchestrator',
    };
}
function estimateTextTokens(text) {
    return estimateTokens(text);
}
