import { ANTIGRAVITY_GLOBAL_ALIAS_KEY, cacheAntigravitySessionSignature, getAntigravityRequestSessionMeta } from '../antigravity-session-signature.js';
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function resolveStableSessionId(adapterContext) {
    if (!adapterContext) {
        return undefined;
    }
    const ctxAny = adapterContext;
    const candidates = [ctxAny.sessionId, ctxAny.conversationId].filter((v) => typeof v === 'string');
    const raw = candidates.map((s) => s.trim()).find((s) => s.length > 0);
    if (!raw) {
        return undefined;
    }
    // Antigravity-Manager alignment: never hash/derive session ids from external session/conversation identifiers here.
    // If the caller already provides a proper fingerprint (sid-*), we can use it as a last-resort fallback.
    return raw.toLowerCase().startsWith('sid-') ? raw : undefined;
}
function resolveAntigravityAliasKey(adapterContext) {
    if (!adapterContext) {
        return 'antigravity.unknown';
    }
    const ctxAny = adapterContext;
    const candidates = [ctxAny.runtimeKey, ctxAny.providerKey, ctxAny.providerId].filter((v) => typeof v === 'string');
    for (const value of candidates) {
        const trimmed = value.trim();
        if (!trimmed)
            continue;
        const lower = trimmed.toLowerCase();
        if (lower.startsWith('antigravity.')) {
            const parts = trimmed.split('.');
            if (parts.length >= 2 && parts[0] && parts[1]) {
                return `${parts[0].trim()}.${parts[1].trim()}`;
            }
        }
        return trimmed;
    }
    return 'antigravity.unknown';
}
function shouldEnableForAdapter(adapterContext) {
    if (!adapterContext) {
        return false;
    }
    const protocol = typeof adapterContext.providerProtocol === 'string' ? adapterContext.providerProtocol.trim().toLowerCase() : '';
    if (protocol !== 'gemini-chat') {
        return false;
    }
    const ctxAny = adapterContext;
    const providerIdOrKeyRaw = typeof ctxAny.providerId === 'string'
        ? String(ctxAny.providerId)
        : typeof ctxAny.providerKey === 'string'
            ? String(ctxAny.providerKey)
            : typeof ctxAny.runtimeKey === 'string'
                ? String(ctxAny.runtimeKey)
                : '';
    const providerIdOrKey = providerIdOrKeyRaw.trim().toLowerCase();
    const effectiveProviderId = providerIdOrKey.split('.')[0] ?? '';
    // Antigravity-Manager alignment: thoughtSignature compat applies to both Antigravity and Gemini CLI.
    return effectiveProviderId === 'antigravity' || effectiveProviderId === 'gemini-cli';
}
export function cacheAntigravityThoughtSignatureFromGeminiResponse(payload, adapterContext) {
    if (!shouldEnableForAdapter(adapterContext)) {
        return payload;
    }
    const fallbackAliasKey = resolveAntigravityAliasKey(adapterContext);
    const ctxAny = adapterContext;
    const payloadAny = payload;
    const keyCandidates = [
        adapterContext?.requestId,
        typeof ctxAny.clientRequestId === 'string' ? String(ctxAny.clientRequestId) : '',
        typeof ctxAny.groupRequestId === 'string' ? String(ctxAny.groupRequestId) : '',
        typeof payloadAny.request_id === 'string' ? String(payloadAny.request_id) : '',
        typeof payloadAny.requestId === 'string' ? String(payloadAny.requestId) : ''
    ].filter((k) => typeof k === 'string' && k.trim().length);
    let aliasKey = fallbackAliasKey;
    let sessionId = '';
    let messageCount = 1;
    for (const key of keyCandidates) {
        const resolved = getAntigravityRequestSessionMeta(key);
        if (resolved && resolved.sessionId.trim().length) {
            aliasKey = typeof resolved.aliasKey === 'string' && resolved.aliasKey.trim().length ? resolved.aliasKey.trim() : fallbackAliasKey;
            sessionId = resolved.sessionId.trim();
            messageCount = resolved.messageCount;
            break;
        }
    }
    if (!sessionId) {
        const stable = resolveStableSessionId(adapterContext);
        if (stable) {
            sessionId = stable;
            messageCount = 1;
        }
    }
    if (!sessionId) {
        return payload;
    }
    const candidatesRaw = payload.candidates;
    const candidates = Array.isArray(candidatesRaw) ? candidatesRaw : [];
    for (const candidate of candidates) {
        const content = isRecord(candidate.content) ? candidate.content : undefined;
        const partsRaw = content?.parts;
        const parts = Array.isArray(partsRaw) ? partsRaw : [];
        for (const part of parts) {
            const sig = typeof part.thoughtSignature === 'string'
                ? String(part.thoughtSignature)
                : typeof part.thought_signature === 'string'
                    ? String(part.thought_signature)
                    : '';
            if (sig.trim().length) {
                cacheAntigravitySessionSignature(aliasKey, sessionId, sig.trim(), messageCount);
                // Antigravity-Manager alignment: also store into the global signature store for this session.
                if (aliasKey !== ANTIGRAVITY_GLOBAL_ALIAS_KEY) {
                    cacheAntigravitySessionSignature(ANTIGRAVITY_GLOBAL_ALIAS_KEY, sessionId, sig.trim(), messageCount);
                }
            }
        }
    }
    return payload;
}
