"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateMemoryInsights = generateMemoryInsights;
exports.getInsightSummary = getInsightSummary;
const database_1 = require("../database/database");
function generateMemoryInsights(project, days = 30) {
    const db = (0, database_1.getDb)();
    const insights = [];
    const since = new Date(Date.now() - days * 86400000).toISOString();
    // 1. Trend Analysis — is activity increasing or decreasing?
    const trends = analyzeTrends(project, days);
    if (trends.length >= 2) {
        const recent = trends[trends.length - 1];
        const prev = trends[trends.length - 2];
        if (recent.eventCount > prev.eventCount * 1.5) {
            insights.push({
                type: 'trend',
                severity: 'info',
                title: 'Activity spike detected',
                description: `Activity increased ${Math.round((recent.eventCount / prev.eventCount - 1) * 100)}% from ${prev.period} to ${recent.period}`,
                evidence: [`${prev.period}: ${prev.eventCount} events`, `${recent.period}: ${recent.eventCount} events`],
                confidence: 0.8,
                category: 'productivity',
                createdAt: new Date().toISOString(),
            });
        }
        else if (recent.eventCount < prev.eventCount * 0.5 && prev.eventCount > 5) {
            insights.push({
                type: 'trend',
                severity: 'warning',
                title: 'Activity drop detected',
                description: `Activity dropped ${Math.round((1 - recent.eventCount / prev.eventCount) * 100)}% — possible blocker or context switch`,
                evidence: [`${prev.period}: ${prev.eventCount} events`, `${recent.period}: ${recent.eventCount} events`],
                confidence: 0.7,
                category: 'productivity',
                createdAt: new Date().toISOString(),
            });
        }
    }
    // 2. Error Pattern — repeated errors in same area
    const errorPattern = detectErrorPatterns(project, since);
    if (errorPattern)
        insights.push(errorPattern);
    // 3. Decision Velocity — are decisions being made?
    const decisionInsight = analyzeDecisionVelocity(project, since);
    if (decisionInsight)
        insights.push(decisionInsight);
    // 4. File Risk — files with too many events (hotspot)
    const hotspots = detectHotspots(project, since);
    insights.push(...hotspots);
    // 5. Milestone — total events milestone
    const totalRow = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ?').get(project);
    if (totalRow.c > 0 && totalRow.c % 100 === 0) {
        insights.push({
            type: 'milestone',
            severity: 'info',
            title: `Memory milestone: ${totalRow.c} events`,
            description: `Project "${project}" has accumulated ${totalRow.c} memory events`,
            evidence: [`${totalRow.c} total events`],
            confidence: 1.0,
            category: 'growth',
            createdAt: new Date().toISOString(),
        });
    }
    // 6. Style Consistency — check if verification commands are being used
    const styleInsight = analyzeStyleConsistency(project);
    if (styleInsight)
        insights.push(styleInsight);
    return insights.sort((a, b) => {
        const sevOrder = { critical: 0, warning: 1, info: 2 };
        return sevOrder[a.severity] - sevOrder[b.severity];
    });
}
function analyzeTrends(project, days) {
    const db = (0, database_1.getDb)();
    const weeks = Math.ceil(days / 7);
    const trends = [];
    for (let w = weeks - 1; w >= 0; w--) {
        const weekStart = new Date(Date.now() - (w + 1) * 7 * 86400000);
        const weekEnd = new Date(Date.now() - w * 7 * 86400000);
        const startStr = weekStart.toISOString().slice(0, 10);
        const endStr = weekEnd.toISOString().slice(0, 10);
        const row = db.prepare(`
      SELECT COUNT(*) as c, AVG(importance) as avg_imp,
             SUM(CASE WHEN type = 'error' THEN 1 ELSE 0 END) as errors,
             SUM(CASE WHEN type = 'decision' THEN 1 ELSE 0 END) as decisions
      FROM memory_events
      WHERE project = ? AND date(created_at) BETWEEN date(?) AND date(?)
    `).get(project, startStr, endStr);
        const topTypeRow = db.prepare(`
      SELECT type, COUNT(*) as c FROM memory_events
      WHERE project = ? AND date(created_at) BETWEEN date(?) AND date(?)
      GROUP BY type ORDER BY c DESC LIMIT 1
    `).get(project, startStr, endStr);
        trends.push({
            period: `${startStr}_to_${endStr}`,
            eventCount: row.c,
            avgImportance: Math.round((row.avg_imp || 0) * 10) / 10,
            topType: topTypeRow?.type || 'none',
            errorRate: row.c > 0 ? Math.round(row.errors / row.c * 100) : 0,
            decisionRate: row.c > 0 ? Math.round(row.decisions / row.c * 100) : 0,
        });
    }
    return trends;
}
function detectErrorPatterns(project, since) {
    const db = (0, database_1.getDb)();
    const errors = db.prepare(`
    SELECT summary, topic, COUNT(*) as c FROM memory_events
    WHERE project = ? AND type = 'error' AND created_at >= ?
    GROUP BY summary HAVING c >= 2
    ORDER BY c DESC LIMIT 5
  `).all(project, since);
    if (errors.length === 0)
        return null;
    return {
        type: 'risk',
        severity: 'warning',
        title: 'Repeated error patterns detected',
        description: `${errors.length} error pattern(s) occurred multiple times — may need systematic fix`,
        evidence: errors.map(e => `${e.c}x: ${e.summary}`),
        confidence: 0.85,
        category: 'quality',
        createdAt: new Date().toISOString(),
    };
}
function analyzeDecisionVelocity(project, since) {
    const db = (0, database_1.getDb)();
    const row = db.prepare(`
    SELECT COUNT(*) as c FROM memory_events
    WHERE project = ? AND type = 'decision' AND created_at >= ?
  `).get(project, since);
    const totalRow = db.prepare(`
    SELECT COUNT(*) as c FROM memory_events
    WHERE project = ? AND created_at >= ?
  `).get(project, since);
    if (totalRow.c < 10)
        return null;
    const decisionRate = totalRow.c > 0 ? row.c / totalRow.c : 0;
    if (decisionRate < 0.05 && totalRow.c > 20) {
        return {
            type: 'recommendation',
            severity: 'info',
            title: 'Low decision logging',
            description: `Only ${Math.round(decisionRate * 100)}% of events are decisions — consider logging more decisions for better memory`,
            evidence: [`${row.c} decisions out of ${totalRow.c} events`],
            confidence: 0.6,
            category: 'process',
            createdAt: new Date().toISOString(),
        };
    }
    return null;
}
function detectHotspots(project, since) {
    const db = (0, database_1.getDb)();
    const insights = [];
    const hotspots = db.prepare(`
    SELECT files_json, COUNT(*) as c, AVG(importance) as avg_imp
    FROM memory_events
    WHERE project = ? AND files_json IS NOT NULL AND created_at >= ?
    GROUP BY files_json
    HAVING c >= 3
    ORDER BY c DESC LIMIT 3
  `).all(project, since);
    for (const hs of hotspots) {
        try {
            const files = JSON.parse(hs.files_json);
            if (files.length > 0) {
                insights.push({
                    type: 'risk',
                    severity: hs.avg_imp >= 7 ? 'warning' : 'info',
                    title: `Hotspot: ${files[0]}`,
                    description: `File touched ${hs.c} times with avg importance ${Math.round(hs.avg_imp * 10) / 10} — may need refactoring`,
                    evidence: [`${hs.c} events`, `Avg importance: ${hs.avg_imp}`],
                    confidence: 0.7,
                    category: 'code-health',
                    createdAt: new Date().toISOString(),
                });
            }
        }
        catch { }
    }
    return insights;
}
function analyzeStyleConsistency(project) {
    const db = (0, database_1.getDb)();
    const editCount = db.prepare("SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND type = 'edit'").get(project);
    const verificationCount = db.prepare("SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND type = 'verification'").get(project);
    if (editCount.c > 10 && verificationCount.c === 0) {
        return {
            type: 'recommendation',
            severity: 'warning',
            title: 'No verification events logged',
            description: `${editCount.c} edits but no verifications — consider logging test/lint runs`,
            evidence: [`${editCount.c} edits, 0 verifications`],
            confidence: 0.6,
            category: 'quality',
            createdAt: new Date().toISOString(),
        };
    }
    return null;
}
function getInsightSummary(project, days = 30) {
    const insights = generateMemoryInsights(project, days);
    const byType = {};
    const bySeverity = {};
    for (const i of insights) {
        byType[i.type] = (byType[i.type] || 0) + 1;
        bySeverity[i.severity] = (bySeverity[i.severity] || 0) + 1;
    }
    return {
        total: insights.length,
        byType,
        bySeverity,
        topInsights: insights.slice(0, 5),
    };
}
//# sourceMappingURL=memory-insights.js.map