// tools/spec-usage-report.ts — Handler for the spec_usage_report MCP tool (SPEC-158)
// Returns spec observability data: hot specs, cold specs, tool matrix, hot ACs.
import { specObservabilityStore, specStore } from '../storage/index.js';
import { buildObservabilityReport } from '../engine/spec-observability/index.js';
import { addNextSteps, formatSuccess } from './response-helpers.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function renderMetricsTable(report, specId) {
    const lines = [];
    if (specId !== undefined) {
        const metric = report.specMetrics.find((m) => m.specId === specId.toUpperCase());
        if (!metric) {
            return `No usage data found for ${specId} in the selected period.`;
        }
        lines.push(`### ${metric.specId}`);
        lines.push(`- **Total accesses**: ${String(metric.totalAccesses)}`);
        lines.push(`- **Last accessed**: ${metric.lastAccessAt}`);
        lines.push(`- **Tools used**: ${metric.toolsUsed.join(', ')}`);
        if (metric.hotAcs.length > 0) {
            lines.push('- **Hot ACs**:');
            for (const ac of metric.hotAcs) {
                lines.push(`  - ${ac.acRef}: ${String(ac.count)} refs`);
            }
        }
        const toolRows = Object.entries(metric.toolMatrix)
            .sort((a, b) => b[1] - a[1])
            .map(([tool, count]) => `  | ${tool} | ${String(count)} |`)
            .join('\n');
        if (toolRows.length > 0) {
            lines.push('- **Tool usage matrix**:');
            lines.push('  | Tool | Calls |');
            lines.push('  |------|-------|');
            lines.push(toolRows);
        }
        return lines.join('\n');
    }
    // Full report
    lines.push(`**Period**: ${report.period}  |  **Total events**: ${String(report.totalEvents)}`);
    lines.push('');
    if (report.hotSpecs.length > 0) {
        lines.push('### Hot Specs (most accessed)');
        lines.push('| Spec | Accesses | Last Access |');
        lines.push('|------|----------|-------------|');
        for (const m of report.hotSpecs) {
            lines.push(`| ${m.specId} | ${String(m.totalAccesses)} | ${m.lastAccessAt.slice(0, 10)} |`);
        }
        lines.push('');
    }
    if (report.coldSpecs.length > 0) {
        lines.push('### Cold Specs (approved but never accessed)');
        lines.push(report.coldSpecs.map((id) => `- ${id}`).join('\n'));
        lines.push('');
    }
    if (report.topTools.length > 0) {
        lines.push('### Top Tools (by spec references)');
        lines.push('| Tool | Refs |');
        lines.push('|------|------|');
        for (const t of report.topTools.slice(0, 10)) {
            lines.push(`| ${t.toolName} | ${String(t.count)} |`);
        }
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleSpecUsageReport(args) {
    const { projectId, specId, period = 'week' } = args;
    // Load events and known specs in parallel
    const [log, specs] = await Promise.all([
        specObservabilityStore.getSpecUsageLog(projectId),
        specStore.listSpecs(projectId).catch(() => []),
    ]);
    const allKnownSpecIds = specs
        .filter((s) => s.status === 'approved' || s.status === 'implementing' || s.status === 'done')
        .map((s) => s.id);
    const report = buildObservabilityReport({
        projectId,
        period,
        events: log.events,
        allKnownSpecIds,
        filterSpecId: specId,
    });
    const body = renderMetricsTable(report, specId);
    const title = specId !== undefined ? `Spec Observability — ${specId}` : 'Spec Observability Report';
    const text = formatSuccess(title, body);
    const withNextSteps = addNextSteps(text, [
        'Run `list_specs` to see all specs with their statuses',
        'Use `spec_usage_report` with a specific specId for per-spec drill-down',
        'Track implementation progress with `validate`',
    ]);
    return { content: [{ type: 'text', text: withNextSteps }] };
}
//# sourceMappingURL=spec-usage-report.js.map