// tools/velocity-handler.ts — Handlers for velocity_report and velocity_trend (SPEC-288)
import { listSpecs } from '../storage/spec-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { buildVelocityReport, buildVelocityTrend } from '../engine/velocity-calculator.js';
import { formatSuccess, formatError, toolResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// velocity_report handler
// ---------------------------------------------------------------------------
export async function handleVelocityReport(args) {
    if (!args.projectPath || args.projectPath.trim().length === 0) {
        return toolResult(formatError('projectPath is required', 'Provide the absolute path to your project root.'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const weeks = Math.min(Math.max(args.weeks ?? 8, 1), 52);
    const specs = await listSpecs(projectId);
    const filters = {
        weeks,
        scope: args.scope,
        type: args.type,
    };
    const report = buildVelocityReport(specs, projectId, args.projectPath, filters);
    const lines = [
        `Velocity Report — ${args.projectPath}`,
        `Period: last ${String(weeks)} weeks | Total specs: ${String(report.totalSpecs)}`,
        '',
        report.summary,
        '',
    ];
    // Throughput table
    lines.push('**Weekly Throughput:**');
    for (const w of report.throughput) {
        const bar = '#'.repeat(w.specsCompleted);
        lines.push(`  ${w.weekLabel}: ${String(w.specsCompleted).padStart(2)} ${bar}`);
    }
    // Lead time
    if (report.leadTime !== null) {
        const lt = report.leadTime;
        lines.push('');
        lines.push(`**Lead Time** (${String(lt.sampleSize)} specs):`);
        lines.push(`  Avg: ${(lt.avgHours / 24).toFixed(1)} days | Median: ${(lt.medianHours / 24).toFixed(1)} days`);
        lines.push(`  Min: ${(lt.minHours / 24).toFixed(1)} days | Max: ${(lt.maxHours / 24).toFixed(1)} days`);
    }
    // Cycle time
    if (report.cycleTime !== null) {
        const ct = report.cycleTime;
        lines.push('');
        lines.push(`**Cycle Time** (${String(ct.sampleSize)} specs):`);
        lines.push(`  Avg: ${(ct.avgHours / 24).toFixed(1)} days | Median: ${(ct.medianHours / 24).toFixed(1)} days`);
    }
    // Flow efficiency
    if (report.flowEfficiency !== null) {
        const fe = report.flowEfficiency;
        lines.push('');
        lines.push(`**Flow Efficiency:** ${(fe.efficiency * 100).toFixed(0)}%`);
    }
    // WIP
    lines.push('');
    lines.push(`**WIP:** ${String(report.wip.current)} specs in progress`);
    if (report.wip.current > 0) {
        lines.push(`  Avg age: ${(report.wip.avgAgeHours / 24).toFixed(1)} days`);
    }
    const body = lines.join('\n');
    return toolResult(formatSuccess('Velocity Report', body), report);
}
// ---------------------------------------------------------------------------
// velocity_trend handler
// ---------------------------------------------------------------------------
export async function handleVelocityTrend(args) {
    if (!args.projectPath || args.projectPath.trim().length === 0) {
        return toolResult(formatError('projectPath is required', 'Provide the absolute path to your project root.'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const compareWeeks = Math.min(Math.max(args.compareWeeks ?? 4, 1), 26);
    const specs = await listSpecs(projectId);
    const filters = {
        weeks: compareWeeks * 2,
        scope: args.scope,
        type: args.type,
    };
    const trend = buildVelocityTrend(specs, projectId, args.projectPath, filters, compareWeeks);
    const trendIcon = trend.trend === 'improving' ? '↑' : trend.trend === 'declining' ? '↓' : '→';
    const lines = [
        `Velocity Trend — ${args.projectPath}`,
        `Comparing last ${String(compareWeeks)} weeks vs previous ${String(compareWeeks)} weeks`,
        '',
        `${trendIcon} ${trend.summary}`,
        '',
        `**Recent (${trend.recent.label}):**`,
        `  ${trend.recent.avgThroughputPerWeek.toFixed(1)} specs/week | ${String(trend.recent.totalDone)} done`,
        trend.recent.avgLeadTimeHours !== null
            ? `  Lead time avg: ${(trend.recent.avgLeadTimeHours / 24).toFixed(1)} days`
            : '',
        '',
        `**Previous (${trend.previous.label}):**`,
        `  ${trend.previous.avgThroughputPerWeek.toFixed(1)} specs/week | ${String(trend.previous.totalDone)} done`,
        trend.previous.avgLeadTimeHours !== null
            ? `  Lead time avg: ${(trend.previous.avgLeadTimeHours / 24).toFixed(1)} days`
            : '',
    ].filter((l) => l !== '');
    const body = lines.join('\n');
    return toolResult(formatSuccess('Velocity Trend', body), trend);
}
//# sourceMappingURL=velocity-handler.js.map