// engine/registry/reporter.ts — Builds the SpecAccuracyReport from validation results
/** Threshold (days) beyond which a registry entry is considered stale. */
const STALE_DAYS = 180;
const MS_PER_DAY = 86_400_000;
/** Calculate score as percentage of references that were validated (not unknown). */
function calculateScore(results) {
    if (results.length === 0) {
        return 100;
    }
    const validated = results.filter((r) => r.status !== 'unknown').length;
    return Math.round((validated / results.length) * 100);
}
/** Extract unique issues from validation results (skip valid ones). */
function collectIssues(results) {
    const seen = new Set();
    const issues = [];
    for (const result of results) {
        if (result.status === 'valid' || !result.issue) {
            continue;
        }
        const key = `${result.issue.type}::${result.issue.framework}::${result.issue.reference}`;
        if (!seen.has(key)) {
            seen.add(key);
            issues.push(result.issue);
        }
    }
    return issues;
}
/** Find registry entries that haven't been updated in more than 180 days. */
function detectStaleEntries(frameworkIds, registry) {
    const now = Date.now();
    return frameworkIds.filter((id) => {
        const entry = registry.get(id);
        /* v8 ignore next 2 — defensive guard; callers pass IDs from detectFrameworks() which already filters by registry */
        if (!entry) {
            return false;
        }
        const updated = new Date(entry.lastUpdated).getTime();
        return !isNaN(updated) && now - updated > STALE_DAYS * MS_PER_DAY;
    });
}
/**
 * Build the full SpecAccuracyReport from validation results and metadata.
 */
export function buildReport(results, frameworksDetected, frameworksNotInRegistry, registry) {
    const issues = collectIssues(results);
    const score = calculateScore(results);
    const validatedReferences = results.filter((r) => r.status !== 'unknown').length;
    const staleRegistryEntries = detectStaleEntries(frameworksDetected, registry);
    return {
        score,
        issues,
        frameworksDetected,
        frameworksNotInRegistry,
        totalReferencesChecked: results.length,
        validatedReferences,
        staleRegistryEntries,
    };
}
/**
 * Format a SpecAccuracyReport as a Markdown string for display in MCP response.
 */
export function formatReport(report) {
    const lines = [];
    lines.push('## Spec Accuracy Report');
    lines.push('');
    lines.push(`**Score de confianza:** ${report.score}/100`);
    lines.push(`**Referencias analizadas:** ${report.totalReferencesChecked}`);
    lines.push(`**Referencias validadas:** ${report.validatedReferences}`);
    lines.push('');
    if (report.frameworksDetected.length > 0) {
        lines.push(`**Frameworks detectados:** ${report.frameworksDetected.join(', ')}`);
    }
    if (report.frameworksNotInRegistry.length > 0) {
        lines.push('');
        lines.push('### Advertencias — Frameworks no en registry');
        lines.push('');
        for (const fw of report.frameworksNotInRegistry) {
            lines.push(`- Framework '${fw}' no encontrado en el registry — las referencias a su API no pudieron ser validadas`);
        }
    }
    if (report.staleRegistryEntries.length > 0) {
        lines.push('');
        lines.push('### Advertencias — Entradas desactualizadas');
        lines.push('');
        for (const fw of report.staleRegistryEntries) {
            lines.push(`- La entrada de '${fw}' tiene mas de 180 dias sin actualizar — verificar si los patrones siguen vigentes`);
        }
    }
    const errors = report.issues.filter((i) => i.severity === 'error');
    const warnings = report.issues.filter((i) => i.severity === 'warning');
    const infos = report.issues.filter((i) => i.severity === 'info');
    if (errors.length > 0) {
        lines.push('');
        lines.push('### Errores detectados');
        lines.push('');
        for (const issue of errors) {
            lines.push(`- **[${issue.framework}]** \`${issue.reference}\``);
            if (issue.suggestion) {
                lines.push(`  - Sugerencia: ${issue.suggestion}`);
            }
        }
    }
    if (warnings.length > 0) {
        lines.push('');
        lines.push('### Advertencias de patrones');
        lines.push('');
        for (const issue of warnings) {
            lines.push(`- **[${issue.framework}]** \`${issue.reference}\``);
            if (issue.suggestion) {
                lines.push(`  - Sugerencia: ${issue.suggestion}`);
            }
        }
    }
    if (infos.length > 0) {
        lines.push('');
        lines.push('### Informacion adicional');
        lines.push('');
        for (const issue of infos) {
            lines.push(`- **[${issue.framework}]** ${issue.reference}`);
            if (issue.suggestion) {
                lines.push(`  - ${issue.suggestion}`);
            }
        }
    }
    if (report.issues.length === 0) {
        lines.push('');
        lines.push('No se detectaron problemas en las referencias analizadas.');
    }
    return lines.join('\n');
}
//# sourceMappingURL=reporter.js.map