"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateProactiveAlerts = generateProactiveAlerts;
exports.getAlertSummary = getAlertSummary;
const database_1 = require("../database/database");
function generateProactiveAlerts(project, days = 14) {
    const db = (0, database_1.getDb)();
    const alerts = [];
    const since = new Date(Date.now() - days * 86400000).toISOString();
    // 1. Repeat mistakes — same error summary multiple times
    const repeatErrors = db.prepare(`
    SELECT summary, COUNT(*) as c FROM memory_events
    WHERE project = ? AND type = 'error' AND created_at >= ?
    GROUP BY summary HAVING c >= 3
    ORDER BY c DESC LIMIT 5
  `).all(project, since);
    for (const e of repeatErrors) {
        alerts.push({
            type: 'repeat_mistake',
            severity: e.c >= 5 ? 'critical' : 'warning',
            title: `Repeated error: "${e.summary.slice(0, 60)}"`,
            description: `This error occurred ${e.c} times in ${days} days — systematic fix needed`,
            suggestion: 'Create a fix and log it with cell memory record --type fix',
            confidence: 0.85,
            evidence: [`${e.c} occurrences`],
            createdAt: new Date().toISOString(),
        });
    }
    // 2. Error spike — error rate > 30% of total events
    const statsRow = db.prepare(`
    SELECT
      COUNT(*) as total,
      SUM(CASE WHEN type = 'error' THEN 1 ELSE 0 END) as errors,
      SUM(CASE WHEN type = 'fix' THEN 1 ELSE 0 END) as fixes
    FROM memory_events
    WHERE project = ? AND created_at >= ?
  `).get(project, since);
    if (statsRow.total > 10) {
        const errorRate = statsRow.errors / statsRow.total;
        if (errorRate > 0.3) {
            alerts.push({
                type: 'error_spike',
                severity: 'critical',
                title: `High error rate: ${Math.round(errorRate * 100)}%`,
                description: `${statsRow.errors} errors out of ${statsRow.total} events — code quality dropping`,
                suggestion: 'Pause feature work, focus on fixes and testing',
                confidence: 0.9,
                evidence: [`${statsRow.errors} errors`, `${statsRow.fixes} fixes`, `Rate: ${Math.round(errorRate * 100)}%`],
                createdAt: new Date().toISOString(),
            });
        }
    }
    // 3. Stalled handoff — no updates in 3+ days
    const handoffRow = db.prepare(`
    SELECT MAX(created_at) as last_update FROM memory_events
    WHERE project = ? AND type = 'handoff'
  `).get(project);
    if (handoffRow?.last_update) {
        const daysSince = (Date.now() - new Date(handoffRow.last_update).getTime()) / 86400000;
        if (daysSince > 3) {
            alerts.push({
                type: 'stalled_handoff',
                severity: 'warning',
                title: `Handoff stale: ${Math.round(daysSince)} days old`,
                description: 'No handoff updates recently — context may be lost',
                suggestion: 'Run cell handoff --log to update current context',
                confidence: 0.7,
                evidence: [`Last update: ${handoffRow.last_update}`],
                createdAt: new Date().toISOString(),
            });
        }
    }
    // 4. Low verification — many edits but no verifications
    const editCount = db.prepare("SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND type = 'edit' AND created_at >= ?").get(project, since);
    const verifCount = db.prepare("SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND type = 'verification' AND created_at >= ?").get(project, since);
    if (editCount.c > 15 && verifCount.c === 0) {
        alerts.push({
            type: 'low_verification',
            severity: 'warning',
            title: `${editCount.c} edits but zero verifications`,
            description: 'No test/lint/build verifications logged — bugs may slip through',
            suggestion: 'Log verifications with cell memory record --type verification',
            confidence: 0.75,
            evidence: [`${editCount.c} edits`, '0 verifications'],
            createdAt: new Date().toISOString(),
        });
    }
    // 5. File hotspot — one file touched > 10 times
    const hotspots = db.prepare(`
    SELECT files_json, COUNT(*) as c FROM memory_events
    WHERE project = ? AND files_json IS NOT NULL AND created_at >= ?
    GROUP BY files_json HAVING c >= 10
    ORDER BY c DESC LIMIT 3
  `).all(project, since);
    for (const h of hotspots) {
        try {
            const files = JSON.parse(h.files_json);
            if (files.length > 0) {
                alerts.push({
                    type: 'file_hotspot',
                    severity: 'info',
                    title: `Hotspot: ${files[0]}`,
                    description: `File touched ${h.c} times — may need refactoring or splitting`,
                    suggestion: 'Consider extracting a separate module',
                    confidence: 0.65,
                    evidence: [`${h.c} edits to same file`],
                    createdAt: new Date().toISOString(),
                });
            }
        }
        catch { }
    }
    // 6. Decision gap — many events but no decisions logged
    const decisionCount = db.prepare("SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND type = 'decision' AND created_at >= ?").get(project, since);
    if (statsRow.total > 30 && decisionCount.c === 0) {
        alerts.push({
            type: 'decision_gap',
            severity: 'info',
            title: 'No decisions logged',
            description: `${statsRow.total} events but zero decisions — memory won't capture reasoning`,
            suggestion: 'Log key decisions with cell memory record --type decision',
            confidence: 0.6,
            evidence: [`${statsRow.total} events`, '0 decisions'],
            createdAt: new Date().toISOString(),
        });
    }
    return alerts.sort((a, b) => {
        const sevOrder = { critical: 0, warning: 1, info: 2 };
        return sevOrder[a.severity] - sevOrder[b.severity];
    });
}
function getAlertSummary(project, days = 14) {
    const alerts = generateProactiveAlerts(project, days);
    return {
        total: alerts.length,
        critical: alerts.filter(a => a.severity === 'critical').length,
        warnings: alerts.filter(a => a.severity === 'warning').length,
        info: alerts.filter(a => a.severity === 'info').length,
        alerts,
    };
}
//# sourceMappingURL=proactive-insights.js.map