import { listSpecs } from '../storage/spec-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { getReleaseNotesConfig, saveReleaseNotesConfig } from '../storage/release-notes-store.js';
import { generateReleaseNotes, filterSpecsByDateRange } from '../engine/release-notes-generator.js';
import { formatSuccess, formatError, toolResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function buildDateRange(fromDate, toDate) {
    const now = new Date();
    const to = toDate ?? now.toISOString();
    const from = fromDate ?? new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();
    return { fromDate: from, toDate: to };
}
function validateProjectPath(projectPath) {
    if (!projectPath || projectPath.trim().length === 0) {
        return formatError('projectPath is required', 'Provide the absolute path to your project root.');
    }
    return null;
}
// ---------------------------------------------------------------------------
// generate_release_notes
// ---------------------------------------------------------------------------
export async function handleGenerateReleaseNotes(input) {
    const pathError = validateProjectPath(input.projectPath);
    if (pathError !== null) {
        return toolResult(pathError, undefined, true);
    }
    const projectId = hashProjectPath(input.projectPath);
    const [specs, savedConfig] = await Promise.all([
        listSpecs(projectId),
        getReleaseNotesConfig(input.projectPath),
    ]);
    // Merge saved config with input (input takes precedence)
    const mergedInput = {
        ...input,
        audience: input.audience ?? savedConfig?.defaultAudience,
        format: input.format ?? savedConfig?.defaultFormat,
    };
    const result = generateReleaseNotes(mergedInput, specs);
    const summary = [
        `Generated release notes for ${String(result.entries.length)} spec(s)`,
        `Audience: ${result.audience} | Format: ${result.format}`,
        result.version ? `Version: ${result.version}` : '',
        `Date range: ${result.dateRange.from.slice(0, 10)} → ${result.dateRange.to.slice(0, 10)}`,
        '',
        result.markdown,
    ]
        .filter((l) => l !== '')
        .join('\n');
    return toolResult(formatSuccess('Release Notes Generated', summary), result);
}
// ---------------------------------------------------------------------------
// preview_release_notes
// ---------------------------------------------------------------------------
export async function handlePreviewReleaseNotes(input) {
    const pathError = validateProjectPath(input.projectPath);
    if (pathError !== null) {
        return toolResult(pathError, undefined, true);
    }
    const projectId = hashProjectPath(input.projectPath);
    const specs = await listSpecs(projectId);
    const { fromDate, toDate } = buildDateRange(input.fromDate, input.toDate);
    const maxEntries = input.maxEntries ?? 10;
    const filtered = filterSpecsByDateRange(specs, fromDate, toDate).slice(0, maxEntries);
    const titles = filtered
        .slice(0, 3)
        .map((s) => `  - [${s.id}] ${s.title}`)
        .join('\n');
    const summary = [
        `Found ${String(filtered.length)} completed spec(s) in range ${fromDate.slice(0, 10)} → ${toDate.slice(0, 10)}`,
        filtered.length > 0 ? `\nFirst ${String(Math.min(3, filtered.length))} entries:` : '',
        titles,
        '',
        `Run generate_release_notes to produce the full release notes document.`,
    ]
        .filter((l) => l !== '')
        .join('\n');
    return toolResult(formatSuccess('Release Notes Preview', summary), {
        totalFound: filtered.length,
        dateRange: { from: fromDate, to: toDate },
        sampleTitles: filtered.slice(0, 3).map((s) => s.title),
    });
}
// ---------------------------------------------------------------------------
// configure_release_notes
// ---------------------------------------------------------------------------
export async function handleConfigureReleaseNotes(input) {
    const pathError = validateProjectPath(input.projectPath);
    if (pathError !== null) {
        return toolResult(pathError, undefined, true);
    }
    const existing = await getReleaseNotesConfig(input.projectPath);
    const defaults = {
        defaultAudience: 'user',
        defaultFormat: 'markdown',
        includeBreakingChanges: true,
        groupByTag: false,
        configuredAt: new Date().toISOString(),
    };
    const base = existing ?? defaults;
    const updated = {
        defaultAudience: input.defaultAudience ?? base.defaultAudience,
        defaultFormat: input.defaultFormat ?? base.defaultFormat,
        includeBreakingChanges: input.includeBreakingChanges ?? base.includeBreakingChanges,
        groupByTag: input.groupByTag ?? base.groupByTag,
        configuredAt: new Date().toISOString(),
    };
    await saveReleaseNotesConfig(input.projectPath, updated);
    const summary = [
        `Default audience: ${updated.defaultAudience}`,
        `Default format: ${updated.defaultFormat}`,
        `Include breaking changes: ${String(updated.includeBreakingChanges)}`,
        `Group by tag: ${String(updated.groupByTag)}`,
    ].join('\n');
    return toolResult(formatSuccess('Release Notes Configured', summary), updated);
}
//# sourceMappingURL=release-notes-handler.js.map