// tools/force-status-analytics.ts — SPEC-969: Query force-usage analytics and generate reports
import { join } from 'node:path';
import { mkdir, writeFile } from 'node:fs/promises';
import { readForceAnalytics } from '../storage/force-analytics-store.js';
import { resolveProjectPath } from '../storage/path-resolver.js';
import { hashProjectPath } from '../storage/base-store.js';
function buildMarkdownReport(projectPath, entries, stats) {
    const lines = [
        '# Quality Exceptions Report',
        '',
        `Generated: ${new Date().toISOString()}`,
        `Project: ${projectPath}`,
        '',
        '## Summary',
        '',
        `- Total specs: ${stats.totalSpecs}`,
        `- Forced specs: ${stats.forcedSpecs}`,
        `- Ratio: ${Math.round(stats.ratio * 100)}%`,
        '',
        '## Forced Transitions',
        '',
        '| Spec | Type | Timestamp | Agent | Reason |',
        '|------|------|-----------|-------|--------|',
    ];
    for (const e of entries) {
        const reason = e.reason.replace(/\|/g, '\\|').replace(/\n/g, ' ');
        lines.push(`| ${e.specId} | ${e.type} | ${e.timestamp} | ${e.agentId} | ${reason.slice(0, 120)}${reason.length > 120 ? '…' : ''} |`);
    }
    if (entries.length === 0) {
        lines.push('*No forced transitions recorded.*');
    }
    lines.push('', '## Recommendations', '', stats.ratio > 0.2
        ? '- ⚠️ More than 20% of specs bypassed gates. Review process health and re-run validate within 24h.'
        : '- ✅ Force usage is within acceptable limits.', '');
    return lines.join('\n');
}
export async function handleForceStatusAnalytics(params) {
    const { projectPath: rawPath, generateReport = false } = params;
    const { projectPath } = await resolveProjectPath(rawPath);
    const projectId = hashProjectPath(projectPath);
    const analytics = await readForceAnalytics(projectId);
    let reportPath = null;
    if (generateReport) {
        try {
            const reportDir = join(projectPath, 'planu', 'reports');
            await mkdir(reportDir, { recursive: true });
            reportPath = join(reportDir, 'quality-exceptions.md');
            const markdown = buildMarkdownReport(projectPath, analytics.forcedTransitions, analytics.stats);
            await writeFile(reportPath, markdown, 'utf-8');
        }
        catch {
            /* best-effort — never block query */
        }
    }
    const textLines = [
        '# Force Status Analytics',
        '',
        `**Project:** ${projectId}`,
        `**Total specs:** ${analytics.stats.totalSpecs}`,
        `**Forced specs:** ${analytics.stats.forcedSpecs}`,
        `**Ratio:** ${Math.round(analytics.stats.ratio * 100)}%`,
        '',
        '## Forced Transitions',
        '',
    ];
    if (analytics.forcedTransitions.length === 0) {
        textLines.push('*No forced transitions recorded.*');
    }
    else {
        for (const t of analytics.forcedTransitions) {
            textLines.push(`- **${t.specId}** (${t.type}) at ${t.timestamp}`);
            textLines.push(`  Agent: ${t.agentId}`);
            textLines.push(`  Reason: ${t.reason.slice(0, 200)}${t.reason.length > 200 ? '…' : ''}`);
        }
    }
    if (reportPath) {
        textLines.push('', `📄 Report written to: ${reportPath}`);
    }
    return {
        content: [{ type: 'text', text: textLines.join('\n') }],
        structuredContent: {
            projectId,
            forcedTransitions: analytics.forcedTransitions,
            stats: analytics.stats,
            reportPath,
        },
    };
}
//# sourceMappingURL=force-status-analytics.js.map