"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePredictions = generatePredictions;
exports.getQuickWarnings = getQuickWarnings;
exports.getUnifiedPredictions = getUnifiedPredictions;
const database_1 = require("../../06-memory/database/database");
// ─── Prediction Engine ───────────────────────────────────────────────────────
function generatePredictions(project) {
    const db = (0, database_1.getDb)();
    const predictions = [];
    // ── 1. Repeat Mistakes ─────────────────────────────────────────────
    const errorQuery = project
        ? `SELECT error_type, error_message, file_path, COUNT(*) as cnt, MAX(occurred_at) as last FROM error_log WHERE (fix_applied IS NULL OR fix_applied = '') AND project = '${project.replace(/'/g, "''")}' GROUP BY error_type, error_message HAVING cnt > 1 ORDER BY cnt DESC LIMIT 10`
        : `SELECT error_type, error_message, file_path, COUNT(*) as cnt, MAX(occurred_at) as last FROM error_log WHERE fix_applied IS NULL OR fix_applied = '' GROUP BY error_type, error_message HAVING cnt > 1 ORDER BY cnt DESC LIMIT 10`;
    const errors = db.prepare(errorQuery).all();
    for (const err of errors) {
        predictions.push({
            type: 'repeat_mistake',
            severity: err.cnt > 3 ? 'critical' : err.cnt > 1 ? 'high' : 'medium',
            message: `"${err.error_message}" — ${err.cnt}x repeated`,
            evidence: `Last: ${err.last}, File: ${err.file_path || 'unknown'}`,
            suggestion: 'Fix pattern, not just instance. Check if root cause is same.',
        });
    }
    // ── 2. Decision Regret (from behavioral + git decisions) ────────────
    const decQuery = project
        ? `SELECT decision, approach, result, worked, context, decided_at FROM decision_log WHERE project = '${project.replace(/'/g, "''")}' ORDER BY decided_at DESC LIMIT 20`
        : 'SELECT decision, approach, result, worked, context, decided_at FROM decision_log ORDER BY decided_at DESC LIMIT 20';
    const decisions = db.prepare(decQuery).all();
    const failedDecisions = decisions.filter(d => !d.worked);
    for (const d of failedDecisions.slice(0, 3)) {
        predictions.push({
            type: 'decision_regret',
            severity: 'medium',
            message: `"${d.decision}" — did not work out`,
            evidence: `Approach: ${d.approach}. Context: ${d.context || 'unknown'}`,
            suggestion: 'Reconsider this approach. Look at alternatives that succeeded.',
        });
    }
    // ── 3. Complexity Trap (from AST nesting depth) ─────────────────────
    const complexQuery = project
        ? `SELECT pattern_value, count FROM code_patterns WHERE pattern_type = 'blind_spot_deep_nesting' AND project = '${project.replace(/'/g, "''")}' ORDER BY count DESC LIMIT 5`
        : `SELECT pattern_value, count FROM code_patterns WHERE pattern_type = 'blind_spot_deep_nesting' ORDER BY count DESC LIMIT 5`;
    const complexFiles = db.prepare(complexQuery).all();
    for (const cf of complexFiles) {
        predictions.push({
            type: 'complexity_trap',
            severity: cf.count > 10 ? 'critical' : 'high',
            message: `Deep nesting detected (${cf.count} levels)`,
            evidence: `${cf.pattern_value}`,
            suggestion: 'Break into smaller functions. Each function should do ONE thing.',
        });
    }
    // ── 4. Energy-Based Prediction (from time patterns in git) ──────────
    // ── 5. Empty Catch Blocks (errors silently swallowed) ───────────────
    const emptyQuery = project
        ? `SELECT pattern_value, count FROM code_patterns WHERE pattern_type = 'blind_spot_empty_catch' AND project = '${project.replace(/'/g, "''")}' ORDER BY count DESC LIMIT 3`
        : `SELECT pattern_value, count FROM code_patterns WHERE pattern_type = 'blind_spot_empty_catch' ORDER BY count DESC LIMIT 3`;
    const emptyCatches = db.prepare(emptyQuery).all();
    const now = new Date();
    const hour = now.getHours();
    const day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][now.getDay()];
    if (hour >= 17 || hour < 8) {
        predictions.push({
            type: 'energy_warning',
            severity: 'medium',
            message: `Late/early coding session (${hour}:00)`,
            evidence: `Day: ${day}. Bug rates typically 2-4x higher outside 9am-5pm.`,
            suggestion: 'Complex logic ke liye morning session better. Abhi sirf simple fixes kar.',
        });
    }
    if (day === 'Fri' && hour >= 15) {
        predictions.push({
            type: 'energy_warning',
            severity: 'high',
            message: `Friday evening coding — take extra care`,
            evidence: 'Friday evening bug rate historically 3-4x higher.',
            suggestion: 'Aaj complex features mat push kar. Simple fixes aur testing kar.',
        });
    }
    // ── Summary ─────────────────────────────────────────────────────────
    const repeatCount = predictions.filter(p => p.type === 'repeat_mistake').length;
    const decisionCount = predictions.filter(p => p.type === 'decision_regret').length;
    const complexityRisk = predictions.filter(p => p.type === 'complexity_trap').length > 0;
    let energyInsight = 'No energy warnings. Keep going! 🚀';
    const energyWarnings = predictions.filter(p => p.type === 'energy_warning');
    if (energyWarnings.length > 0) {
        energyInsight = energyWarnings[0].suggestion;
    }
    return {
        project: project || 'all',
        predictions,
        repeatMistakeCount: repeatCount,
        decisionsToReconsider: decisionCount,
        complexityRisk,
        energyInsight,
        generatedAt: new Date().toISOString(),
    };
}
// ─── Quick Warning (lightweight for real-time) ──────────────────────────────
function getQuickWarnings(project) {
    const report = generatePredictions(project);
    return report.predictions
        .filter(p => p.severity === 'critical' || p.severity === 'high')
        .slice(0, 3)
        .map(p => `⚠ ${p.message} — ${p.suggestion}`);
}
function getUnifiedPredictions(project) {
    const results = [];
    // From predictive-engine.ts
    try {
        const engineReport = generatePredictions(project);
        for (const p of engineReport.predictions) {
            results.push({
                source: 'engine',
                type: p.type,
                severity: p.severity,
                message: p.message,
                confidence: p.severity === 'critical' ? 0.9 : p.severity === 'high' ? 0.7 : 0.5,
            });
        }
    }
    catch { /* ignore */ }
    // From predictive-intelligence.ts (if available)
    try {
        const { detectPreFailureAlerts } = require('./predictive-intelligence');
        const alerts = detectPreFailureAlerts(project);
        for (const a of alerts) {
            results.push({
                source: 'intelligence',
                type: a.type,
                severity: a.severity,
                message: a.message,
                confidence: a.confidence,
            });
        }
    }
    catch { /* module not available */ }
    // Deduplicate by message
    const seen = new Set();
    return results.filter(p => {
        if (seen.has(p.message))
            return false;
        seen.add(p.message);
        return true;
    });
}
//# sourceMappingURL=predictive-engine.js.map