const MAX_CONCURRENT = 2;
const ANALYSIS_TIMEOUT_MS = 5000;
const DEPENDENCY_CHECK_INTERVAL_MS = 86_400_000; // 24 hours
export class BackgroundMonitor {
    analyzer;
    enabled;
    running = 0;
    queue = [];
    moduleStatus = new Map();
    dependencyTimerId = null;
    started = false;
    constructor(deps) {
        this.analyzer = deps.analyzer;
        this.enabled = deps.enabled !== false;
        for (const mod of this.analyzer.getModules()) {
            this.moduleStatus.set(mod.name, {
                name: mod.name,
                lastRunAt: null,
                lastRunDuration: null,
                runCount: 0,
                errorCount: 0,
            });
        }
    }
    start() {
        if (!this.enabled || this.started)
            return;
        this.started = true;
        // Run session_start analysis
        this.triggerAnalysis({ trigger: 'session_start' });
        // Schedule dependency monitoring
        this.dependencyTimerId = setInterval(() => {
            this.triggerAnalysis({ trigger: 'scheduled' });
        }, DEPENDENCY_CHECK_INTERVAL_MS);
    }
    stop() {
        this.started = false;
        this.analyzer.clearDebounce();
        if (this.dependencyTimerId) {
            clearInterval(this.dependencyTimerId);
            this.dependencyTimerId = null;
        }
        for (const item of this.queue) {
            item.resolve();
        }
        this.queue.length = 0;
    }
    async onFileChanged(filePath, content) {
        if (!this.enabled || !this.started)
            return;
        if (!/\.(ts|js|tsx|jsx)$/.test(filePath))
            return;
        await this.triggerAnalysis({
            trigger: 'file_changed',
            filePath,
            fileContent: content,
        });
    }
    async onBuildComplete() {
        if (!this.enabled || !this.started)
            return;
        await this.triggerAnalysis({ trigger: 'build_complete' });
    }
    async runAll(fileContent, filePath) {
        await this.triggerAnalysis({
            trigger: 'manual',
            fileContent,
            filePath,
        });
    }
    getStatus() {
        return Array.from(this.moduleStatus.values());
    }
    isStarted() {
        return this.started;
    }
    isEnabled() {
        return this.enabled;
    }
    getRunningCount() {
        return this.running;
    }
    async triggerAnalysis(context) {
        if (this.running >= MAX_CONCURRENT) {
            await new Promise((resolve) => {
                this.queue.push({ context, resolve });
            });
            if (!this.started)
                return;
        }
        this.running++;
        const start = performance.now();
        try {
            await Promise.race([
                this.analyzer.analyze(context),
                this.createTimeout(),
            ]);
            this.updateModuleStatus(context.trigger, performance.now() - start, false);
        }
        catch {
            this.updateModuleStatus(context.trigger, performance.now() - start, true);
        }
        finally {
            this.running--;
            this.processQueue();
        }
    }
    createTimeout() {
        return new Promise((_, reject) => {
            setTimeout(() => {
                reject(new Error('Analysis timeout'));
            }, ANALYSIS_TIMEOUT_MS);
        });
    }
    processQueue() {
        if (this.queue.length > 0 && this.running < MAX_CONCURRENT) {
            const next = this.queue.shift();
            if (next) {
                next.resolve();
            }
        }
    }
    updateModuleStatus(trigger, duration, error) {
        for (const mod of this.analyzer.getModules()) {
            if (mod.shouldRun(trigger)) {
                const status = this.moduleStatus.get(mod.name);
                if (status) {
                    status.lastRunAt = new Date().toISOString();
                    status.lastRunDuration = duration;
                    status.runCount++;
                    if (error)
                        status.errorCount++;
                }
            }
        }
    }
}
//# sourceMappingURL=BackgroundMonitor.js.map