import { isChatSyncedWithCursor } from './chat-sync.js';
import { isLentaDeliveryPending } from './lenta-delivery.js';
function hasAssistantTail(history) {
    const last = history[history.length - 1];
    return !!last && last.role === 'assistant' && !!(last.text?.trim() || last.html?.trim());
}
/**
 * Push when opening the chat shows a complete turn.
 * When sidebar is idle, do not block on `lenta-pending` (DOM overlay may still churn seq).
 */
export function assessAgentCompletionReadiness(agentId, state, deps, opts) {
    const messages = deps.getDisplayMessages(agentId);
    const history = deps.getJsonlHistory(agentId);
    const subscribed = deps.isSubscribed(agentId);
    const title = deps.getSubscribeTitle(agentId);
    const sidebarIdle = opts?.sidebarIdle === true;
    const turnLimit = deps.getClientTurnLimit?.(agentId);
    if (sidebarIdle && hasAssistantTail(history)) {
        if (subscribed && title && isChatSyncedWithCursor(agentId, title, state)) {
            if (isLentaDeliveryPending(agentId, messages, turnLimit)) {
                return { ready: true, detail: 'jsonl-ready-sidebar-idle' };
            }
            return { ready: true, detail: 'lenta-delivered' };
        }
        return { ready: true, detail: 'jsonl-archive' };
    }
    if (subscribed && title && isChatSyncedWithCursor(agentId, title, state)) {
        if (!messages.length && !history.length) {
            return { ready: false, detail: 'lenta-empty' };
        }
        if (isLentaDeliveryPending(agentId, messages, turnLimit)) {
            return { ready: false, detail: 'lenta-pending' };
        }
        return { ready: true, detail: 'lenta-delivered' };
    }
    if (hasAssistantTail(history)) {
        if (subscribed && messages.length && isLentaDeliveryPending(agentId, messages, turnLimit)) {
            return { ready: false, detail: 'lenta-pending-bg' };
        }
        return { ready: true, detail: 'jsonl-archive' };
    }
    return { ready: false, detail: 'no-archive' };
}
