"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.explainPattern = explainPattern;
exports.explainPatternList = explainPatternList;
const outcome_recorder_1 = require("../decisions/outcome-recorder");
const failure_memory_1 = require("../decisions/failure-memory");
function explainPattern(pattern) {
    const outcomeStats = (0, outcome_recorder_1.getPatternOutcomeStats)(pattern.patternId);
    const failureRecord = (0, failure_memory_1.getFailureRecord)(pattern.patternId);
    const totalSignals = pattern.signals.total;
    const conditions = (pattern.conditions || []).map((c) => ({
        condition: c.type,
        value: c.value,
        score: c.matchScore,
        explanation: explainCondition(c.type, c.value, c.matchScore),
    }));
    const risks = [];
    const tier = getConfidenceTier(pattern.confidence.mean);
    if (tier === 'weak' || tier === 'uncertain') {
        risks.push({
            type: 'low_confidence',
            severity: tier === 'uncertain' ? 'critical' : 'warning',
            message: tier === 'uncertain'
                ? `Very low confidence (${(pattern.confidence.mean * 100).toFixed(0)}%). Further signals needed.`
                : `Low confidence (${(pattern.confidence.mean * 100).toFixed(0)}%). Consider gathering more signals.`,
        });
    }
    if (totalSignals < 5) {
        risks.push({
            type: 'few_signals',
            severity: 'info',
            message: `Only ${totalSignals} signal${totalSignals === 1 ? '' : 's'}. Pattern may not be reliable yet.`,
        });
    }
    if (failureRecord && failureRecord.failureRate >= 0.5 && failureRecord.totalSignals >= 3) {
        risks.push({
            type: 'failure_warning',
            severity: failureRecord.failureRate >= 0.8 ? 'critical' : 'warning',
            message: `${(failureRecord.failureRate * 100).toFixed(0)}% rejection rate across ${failureRecord.totalSignals} signals.`,
        });
    }
    const acceptRate = outcomeStats
        ? outcomeStats.acceptCount / outcomeStats.totalAppearances
        : null;
    const successRate = outcomeStats
        ? outcomeStats.workflowSuccessRate
        : null;
    const fromLines = pattern.from.split('\n').length;
    const toLines = pattern.to.split('\n').length;
    const maxLines = Math.max(fromLines, toLines);
    const timeEstimate = maxLines <= 1 ? '~15s' : maxLines <= 5 ? '~45s' : maxLines <= 15 ? '~2m' : '~5m';
    let recommendation;
    if (risks.some((r) => r.severity === 'critical')) {
        recommendation = `Consider alternatives. This pattern has significant risk factors.`;
    }
    else if (acceptRate !== null && acceptRate > 0.7 && tier === 'strong') {
        recommendation = `Highly recommended. Strong track record with high confidence.`;
    }
    else if (tier === 'strong') {
        recommendation = `Recommended. Strong confidence based on ${totalSignals} signal${totalSignals === 1 ? '' : 's'}.`;
    }
    else if (tier === 'moderate') {
        recommendation = `Potentially useful. Moderate confidence — review context before accepting.`;
    }
    else {
        recommendation = `Insufficient data to make a strong recommendation.`;
    }
    return {
        patternId: pattern.patternId,
        description: pattern.description,
        confidence: {
            tier,
            mean: pattern.confidence.mean,
            ci95: pattern.confidence.ci95,
            signalCount: totalSignals,
            interpretation: explainTier(tier, pattern.confidence.mean, pattern.confidence.ci95),
        },
        conditions,
        outcomes: {
            acceptRate,
            successRate,
            totalTrials: totalSignals,
            timeSavedEstimate: timeEstimate,
        },
        risks,
        recommendation,
    };
}
function explainPatternList(patterns) {
    return patterns.map(explainPattern);
}
function getConfidenceTier(mean) {
    if (mean >= 0.9)
        return 'strong';
    if (mean >= 0.7)
        return 'moderate';
    if (mean >= 0.5)
        return 'weak';
    return 'uncertain';
}
function explainTier(tier, mean, ci95) {
    const range = `[${(ci95[0] * 100).toFixed(0)}%–${(ci95[1] * 100).toFixed(0)}%]`;
    switch (tier) {
        case 'strong':
            return `High confidence (${(mean * 100).toFixed(0)}% ${range}). This pattern has strong statistical backing.`;
        case 'moderate':
            return `Moderate confidence (${(mean * 100).toFixed(0)}% ${range}). Pattern is plausible but needs more signals.`;
        case 'weak':
            return `Weak confidence (${(mean * 100).toFixed(0)}% ${range}). Early-stage pattern, treat as suggestion.`;
        default:
            return `Uncertain (${(mean * 100).toFixed(0)}% ${range}). Insufficient data to evaluate this pattern.`;
    }
}
function explainCondition(type, value, score) {
    const scorePct = score != null ? (score * 100).toFixed(0) : '?';
    switch (type) {
        case 'language':
            return `Applies in ${value} projects (${scorePct}% match)`;
        case 'framework':
            return `Relevant for ${value} framework (${scorePct}% match)`;
        case 'file_type':
            return `Suggested for ${value} files (${scorePct}% match)`;
        case 'strictness':
            return `Best for ${value} linting strictness (${scorePct}% match)`;
        case 'team_convention':
            return `Matches ${value} team convention (${scorePct}% match)`;
        default:
            return `${type}: ${value} (${scorePct}% match)`;
    }
}
//# sourceMappingURL=explainability.js.map