import { getExternalSnapshotForSession } from "../../agents/shared/agent-activity.js";
import { capabilitiesOf } from "./bot-rendering.js";
export async function monitorChannelExternalContexts(options) {
    const contextKeys = new Set([
        ...options.registry.listContexts().map((context) => context.contextKey),
        ...options.promptStore.listContextKeys(),
    ].filter(options.isContextKey));
    for (const contextKey of contextKeys) {
        await monitorChannelExternalContext(options, contextKey);
    }
}
async function monitorChannelExternalContext(options, contextKey) {
    if (!options.canSendSystemMessages(contextKey) || options.isAllowed?.(contextKey) === false) {
        return;
    }
    const queueLength = options.promptStore.list(contextKey).length;
    const paused = options.promptStore.isPaused(contextKey);
    if (queueLength === 0 && options.shouldMonitorContext?.(contextKey) === false) {
        return;
    }
    const session = await options.registry.getOrCreate(contextKey, { deferThreadStart: true }).catch(() => null);
    const context = options.contextForKey(contextKey);
    if (!session || !context) {
        return;
    }
    const shouldDrain = queueLength > 0 && !paused && !session.isProcessing();
    if (!capabilitiesOf(session.getInfo()).externalActivity || !session.getActiveThreadId()) {
        if (shouldDrain) {
            await options.drainQueue(contextKey, context, session);
        }
        return;
    }
    const snapshot = getExternalSnapshotForSession(session, options.config, {
        afterLine: options.previousLastLine(contextKey) ?? Number.MAX_SAFE_INTEGER,
    }) ?? getExternalSnapshotForSession(session, options.config, { maxEvents: 1 });
    if (!snapshot) {
        if (shouldDrain) {
            await options.drainQueue(contextKey, context, session);
        }
        return;
    }
    if (!session.isProcessing()) {
        await options.mirrorSnapshot(contextKey, context, session, snapshot);
    }
    if (snapshot.activity.active) {
        if (queueLength > 0) {
            await options.updateQueueStatus(contextKey, context, `Waiting for ${snapshot.agentLabel} CLI task... ${queueLength} queued${paused ? " (paused)" : ""}.`).catch(() => { });
        }
        return;
    }
    if (shouldDrain) {
        await options.updateQueueStatus(contextKey, context, `CLI task finished, running queued prompt 1/${queueLength}.`).catch(() => { });
        await options.drainQueue(contextKey, context, session);
    }
}
