import { loadTechDebt, saveTechDebtEntry, updateTechDebtEntry, loadTechDebtConfig, saveTechDebtConfig, } from '../storage/tech-debt-store.js';
import { generateDebtId, computeTechDebtMetrics, forecastTechDebt, generateTechDebtReport, filterDebtItems, } from '../engine/tech-debt-manager.js';
import { formatSuccess, formatError, toolResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// track_tech_debt
// ---------------------------------------------------------------------------
export async function handleTrackTechDebt(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const item = {
        id: generateDebtId(),
        specId: args.specId,
        description: args.description,
        estimatedHours: args.estimatedHours,
        severity: args.severity,
        category: args.category,
        status: 'open',
        createdAt: new Date().toISOString(),
    };
    await saveTechDebtEntry(args.projectPath, item);
    const body = [
        `ID: ${item.id}`,
        `Description: ${item.description}`,
        `Severity: ${item.severity} | Category: ${item.category}`,
        `Estimated hours: ${String(item.estimatedHours)}h`,
        item.specId ? `Linked spec: ${item.specId}` : '',
    ]
        .filter(Boolean)
        .join('\n');
    return toolResult(formatSuccess('Tech Debt Tracked', body), item);
}
// ---------------------------------------------------------------------------
// tech_debt_budget
// ---------------------------------------------------------------------------
export async function handleTechDebtBudget(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const config = {
        maxHours: args.maxHours,
        maxPercentOfBacklog: args.maxPercentOfBacklog,
        alertThreshold: args.alertThreshold,
    };
    await saveTechDebtConfig(args.projectPath, config);
    const lines = ['Tech debt budget configured:'];
    if (config.maxHours !== undefined) {
        lines.push(`  Max hours: ${String(config.maxHours)}h`);
    }
    if (config.maxPercentOfBacklog !== undefined) {
        lines.push(`  Max % of backlog: ${String(config.maxPercentOfBacklog)}%`);
    }
    if (config.alertThreshold !== undefined) {
        lines.push(`  Alert threshold: ${String(config.alertThreshold)}%`);
    }
    return toolResult(formatSuccess('Budget Configured', lines.join('\n')), config);
}
// ---------------------------------------------------------------------------
// list_tech_debt
// ---------------------------------------------------------------------------
export async function handleListTechDebt(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const all = await loadTechDebt(args.projectPath);
    const statusFilter = args.status ?? 'open';
    const items = filterDebtItems(all, statusFilter, args.severity, args.category);
    const metrics = computeTechDebtMetrics(all);
    const lines = [
        `Tech Debt — ${args.projectPath}`,
        `Open: ${String(metrics.openItems)} items (${String(metrics.totalOpenHours)}h) | Resolved: ${String(metrics.resolvedItems)}`,
        '',
        `Showing ${String(items.length)} item(s) (filter: ${statusFilter}):`,
    ];
    for (const item of items) {
        lines.push(`  [${item.id}] ${item.severity.toUpperCase()} | ${item.category} | ${String(item.estimatedHours)}h | ${item.description}`);
    }
    if (items.length === 0) {
        lines.push('  No items found.');
    }
    return toolResult(formatSuccess('Tech Debt List', lines.join('\n')), {
        items,
        metrics,
    });
}
// ---------------------------------------------------------------------------
// debt_forecast
// ---------------------------------------------------------------------------
export async function handleDebtForecast(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const items = await loadTechDebt(args.projectPath);
    const config = await loadTechDebtConfig(args.projectPath);
    const forecast = forecastTechDebt(items, config);
    const lines = [
        `Current open hours: ${forecast.currentOpenHours.toFixed(1)}h`,
        `Weekly accumulation rate: ${forecast.weeklyAccumulationRate.toFixed(2)} items/week`,
        `Projected hours in 4 weeks: ${forecast.projectedHoursIn4Weeks.toFixed(1)}h`,
    ];
    if (forecast.budgetMaxHours !== null) {
        lines.push(`Budget max: ${String(forecast.budgetMaxHours)}h`);
    }
    if (forecast.weeksUntilBudgetExceeded !== null) {
        if (forecast.weeksUntilBudgetExceeded === 0) {
            lines.push('Budget already exceeded!');
        }
        else {
            lines.push(`Budget exceeded in: ~${String(forecast.weeksUntilBudgetExceeded)} weeks`);
        }
    }
    else {
        lines.push('No budget limit set.');
    }
    return toolResult(formatSuccess('Debt Forecast', lines.join('\n')), forecast);
}
// ---------------------------------------------------------------------------
// resolve_tech_debt
// ---------------------------------------------------------------------------
export async function handleResolveTechDebt(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    if (!args.id.trim()) {
        return toolResult(formatError('id is required'), undefined, true);
    }
    const updated = await updateTechDebtEntry(args.projectPath, args.id, {
        status: 'resolved',
        resolvedAt: new Date().toISOString(),
        resolvedNotes: args.resolvedNotes,
    });
    if (!updated) {
        return toolResult(formatError(`Tech debt item "${args.id}" not found.`), undefined, true);
    }
    return toolResult(formatSuccess('Tech Debt Resolved', `Item ${args.id} marked as resolved.`), updated);
}
// ---------------------------------------------------------------------------
// tech_debt_report
// ---------------------------------------------------------------------------
export async function handleTechDebtReport(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const items = await loadTechDebt(args.projectPath);
    const config = await loadTechDebtConfig(args.projectPath);
    const html = generateTechDebtReport(items, config);
    const metrics = computeTechDebtMetrics(items);
    return toolResult(formatSuccess('Tech Debt Report', `HTML report generated. Open: ${String(metrics.openItems)} items, ${String(metrics.totalOpenHours)}h total.\n\n${html.slice(0, 200)}...`), { html, metrics });
}
//# sourceMappingURL=tech-debt-handler.js.map