import { getAllOperatives } from '../operatives/crud.js';
import { getMission } from '../missions/crud.js';
import { runSortie } from './runner.js';
export function getRunnableOperatives(db, now = Date.now()) {
    return getAllOperatives(db).filter((operative) => {
        if (!operative.missionId || !['IDLE', 'CHECKOUT'].includes(operative.state)) {
            return false;
        }
        const mission = getMission(db, operative.missionId);
        if (!mission || !['open', 'active'].includes(mission.status)) {
            return false;
        }
        const lastSortieAt = operative.lastSortieAt ? Date.parse(operative.lastSortieAt) : Number.NaN;
        if (Number.isFinite(lastSortieAt) && now - lastSortieAt < operative.sortieIntervalMs) {
            return false;
        }
        return true;
    });
}
export function startSortieScheduler(db, providers) {
    const timer = setInterval(() => {
        const operatives = getRunnableOperatives(db);
        operatives.forEach((operative) => {
            void runSortie(db, operative, providers).catch(() => undefined);
        });
    }, 5_000);
    timer.unref();
    return timer;
}
