import { isExpired } from '../../../modules/claude-invocation/entities/claudeSession/claudeSession.js';
const TERMINAL_AGENT_STATUSES = new Set(['completed', 'failed', 'stopped']);
function agentStatusToOutcome(status) {
    if (status === 'completed')
        return 'completed';
    if (status === 'stopped')
        return 'stopped';
    return 'failed';
}
export function awaitSessionCompletion(input, deps) {
    const { session, timeoutMs, pollIntervalMs } = input;
    const { sessionGateway, completionBridge, now } = deps;
    return new Promise(resolve => {
        let settled = false;
        let pollTimer = null;
        const cleanup = () => {
            completionBridge.unsubscribe(session.jobId);
            if (pollTimer !== null)
                clearTimeout(pollTimer);
        };
        const settle = (completion) => {
            if (settled)
                return;
            settled = true;
            cleanup();
            resolve(completion);
        };
        completionBridge.subscribe(session.jobId, completion => {
            settle({ ...completion, source: completion.source });
        });
        const tick = async () => {
            if (settled)
                return;
            if (isExpired(session, now(), timeoutMs)) {
                settle({ source: 'timeout', outcome: 'failed', reason: 'timeout' });
                return;
            }
            try {
                const agents = await sessionGateway.listAgents();
                const entry = agents.find(item => item.sessionId === session.sessionId);
                if (entry && TERMINAL_AGENT_STATUSES.has(entry.status)) {
                    settle({
                        source: 'polling',
                        outcome: agentStatusToOutcome(entry.status),
                        reason: null,
                    });
                    return;
                }
            }
            catch {
                // polling errors are non-fatal; retry on next tick
            }
            if (!settled) {
                pollTimer = setTimeout(() => {
                    void tick();
                }, pollIntervalMs);
            }
        };
        pollTimer = setTimeout(() => {
            void tick();
        }, pollIntervalMs);
    });
}
//# sourceMappingURL=awaitSessionCompletion.usecase.js.map