import { buildDriftMonitorConfig, buildAlertRules, computeSummaryReport, } from '../engine/drift-monitor.js';
import { getDriftMonitorConfig, saveDriftMonitorConfig, getDriftAlertRules, saveDriftAlertRules, getLastReportAt, updateLastReportAt, } from '../storage/drift-monitor-store.js';
export async function handleConfigureDriftMonitoring(input) {
    if (input.action === 'status') {
        const config = await getDriftMonitorConfig(input.projectPath);
        const rules = await getDriftAlertRules(input.projectPath);
        const lastReportAt = await getLastReportAt(input.projectPath);
        const lines = [
            '**Drift Monitor Status**',
            '',
            `| Field | Value |`,
            `|-------|-------|`,
            `| Enabled | ${config?.enabled ? 'Yes' : 'No'} |`,
            `| Schedule | Every ${config?.scheduleHours ?? 24}h |`,
            `| Threshold | ${config?.threshold ?? 50} |`,
            `| Rules | ${rules.length} |`,
            `| Last Report | ${lastReportAt ?? 'Never'} |`,
        ];
        return { content: [{ type: 'text', text: lines.join('\n') }] };
    }
    const existing = await getDriftMonitorConfig(input.projectPath);
    const currentEnabled = existing?.enabled ?? false;
    const currentSchedule = existing?.scheduleHours ?? 24;
    const currentThreshold = existing?.threshold ?? 50;
    const enabled = input.action === 'enable' ? true : input.action === 'disable' ? false : currentEnabled;
    const config = buildDriftMonitorConfig(input.projectPath, existing, enabled, input.scheduleHours ?? currentSchedule, input.threshold ?? currentThreshold);
    await saveDriftMonitorConfig(input.projectPath, config);
    const actionLabel = input.action === 'enable'
        ? 'Drift monitoring enabled.'
        : input.action === 'disable'
            ? 'Drift monitoring disabled.'
            : input.action === 'set-threshold'
                ? `Threshold set to ${config.threshold}.`
                : `Schedule set to every ${config.scheduleHours}h.`;
    return {
        content: [
            {
                type: 'text',
                text: `${actionLabel}\n\nSchedule: every ${config.scheduleHours}h | Threshold: ${config.threshold} | Updated: ${config.updatedAt}`,
            },
        ],
    };
}
export async function handleDriftAlertRules(input) {
    if (input.action === 'list') {
        const rules = await getDriftAlertRules(input.projectPath);
        if (rules.length === 0) {
            return { content: [{ type: 'text', text: 'No alert rules configured.' }] };
        }
        const lines = ['**Drift Alert Rules**', ''];
        for (const r of rules) {
            lines.push(`- **${r.name}** | Pattern: \`${r.specIdPattern}\` | Threshold: ${r.thresholdOverride ?? 'default'} | Enabled: ${r.enabled ? 'Yes' : 'No'}`);
        }
        return { content: [{ type: 'text', text: lines.join('\n') }] };
    }
    const rulesInput = input.rules ?? [];
    const saved = buildAlertRules(rulesInput);
    await saveDriftAlertRules(input.projectPath, saved);
    return {
        content: [
            {
                type: 'text',
                text: `Saved ${saved.length} alert rule(s).\n\n${saved.map((r) => `- ${r.name} (pattern: ${r.specIdPattern})`).join('\n')}`,
            },
        ],
    };
}
export async function handleDriftSummaryReport(input) {
    const specList = input.specIds ?? [];
    const config = await getDriftMonitorConfig(input.projectPath);
    const rules = await getDriftAlertRules(input.projectPath);
    const report = await computeSummaryReport(input.projectPath, specList, config, rules);
    await updateLastReportAt(input.projectPath, report.generatedAt);
    const lines = [
        '**Drift Summary Report**',
        '',
        `Generated: ${report.generatedAt}`,
        '',
        `| Metric | Value |`,
        `|--------|-------|`,
        `| Total Specs | ${report.totalSpecs} |`,
        `| Drifted | ${report.driftedSpecs} |`,
        `| Clean | ${report.cleanSpecs} |`,
        `| Overall Drift Score | ${report.overallDriftScore}% |`,
    ];
    if (report.alerts.length > 0) {
        lines.push('', '**Alerts**', '');
        for (const alert of report.alerts) {
            const rule = alert.ruleName !== undefined ? ` [${alert.ruleName}]` : '';
            lines.push(`- ${alert.specId}: score ${alert.driftScore}${rule}`);
        }
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
//# sourceMappingURL=drift-monitor-handler.js.map