import { nexusEventBus } from '../../engines/event-bus.js';
import { ArchitectsConfig } from '../config.js';
import { ArchitectsSentinel } from '../sentinel/patrol.js';
export class ArchitectsWard {
    db;
    repoRoot;
    operativeActivity;
    sentinels = new Map();
    criticalStreak = new Map();
    escalations = [];
    timer;
    constructor(db, repoRoot, operativeActivity) {
        this.db = db;
        this.repoRoot = repoRoot;
        this.operativeActivity = operativeActivity;
    }
    registerStrikeTeam(strikeTeamId) {
        if (this.sentinels.has(strikeTeamId))
            return;
        const sentinel = new ArchitectsSentinel(this.db, strikeTeamId, this.repoRoot, this.operativeActivity);
        this.sentinels.set(strikeTeamId, sentinel);
        sentinel.start();
    }
    start() {
        this.timer = setInterval(() => {
            void this.supervise();
        }, ArchitectsConfig.wardPatrolMs);
        this.timer.unref();
    }
    stop() {
        if (this.timer)
            clearInterval(this.timer);
        this.timer = undefined;
        this.sentinels.forEach((sentinel) => sentinel.stop());
    }
    getEscalations() {
        return this.escalations.slice();
    }
    async supervise() {
        for (const [strikeTeamId, sentinel] of this.sentinels) {
            const report = await sentinel.patrol();
            const streak = report.overallHealth === 'critical'
                ? (this.criticalStreak.get(strikeTeamId) ?? 0) + 1
                : 0;
            this.criticalStreak.set(strikeTeamId, streak);
            if (streak >= 2) {
                const escalation = {
                    strikeTeamId,
                    consecutiveCriticalPatrols: streak,
                    message: `Strike Team ${strikeTeamId} critical for ${streak} patrols`,
                    report,
                };
                this.escalations.push(escalation);
                nexusEventBus.emit('architects.ward.escalation', escalation);
                this.criticalStreak.set(strikeTeamId, 0);
            }
        }
        nexusEventBus.emit('architects.ward.patrol', { teamsChecked: this.sentinels.size });
    }
}
