import { watchDirectory } from './file-watcher.js';
import { extractCriteriaFromSpec, buildDriftAlert } from './criteria-checker.js';
// In-memory registry — does not persist across server restarts
const activeWatchers = new Map();
async function runCriteriaCheck(config, filename) {
    const entry = activeWatchers.get(config.specId);
    if (!entry) {
        return;
    }
    const filePath = filename;
    const criteria = await extractCriteriaFromSpec(config.specPath);
    for (const criterion of criteria) {
        const alert = buildDriftAlert(config.specId, criterion, filePath);
        entry.state.alertCount++;
        entry.state.lastAlert = alert;
    }
}
/**
 * Start watching a spec's associated paths for drift.
 * Returns the initial WatcherState.
 */
export function startWatcher(config) {
    const existing = activeWatchers.get(config.specId);
    if (existing) {
        return existing.state;
    }
    const controller = new AbortController();
    const state = {
        specId: config.specId,
        projectPath: config.projectPath,
        active: true,
        startedAt: new Date().toISOString(),
        alertCount: 0,
    };
    activeWatchers.set(config.specId, { state, controller });
    for (const watchedPath of config.watchedPaths) {
        watchDirectory(watchedPath, (filename) => {
            runCriteriaCheck(config, filename).catch(() => {
                // Silently ignore errors during criteria check
            });
        }, controller.signal);
    }
    return state;
}
/**
 * Stop a running watcher. Returns true if it was running, false if not found.
 */
export function stopWatcher(specId) {
    const entry = activeWatchers.get(specId);
    if (!entry) {
        return false;
    }
    entry.controller.abort();
    entry.state.active = false;
    activeWatchers.delete(specId);
    return true;
}
/**
 * Get the current state of a watcher. Returns null if not running.
 */
export function getWatcherState(specId) {
    return activeWatchers.get(specId)?.state ?? null;
}
/**
 * List all active watcher states.
 */
export function listActiveWatchers() {
    return [...activeWatchers.values()].map((e) => e.state);
}
//# sourceMappingURL=index.js.map