import { specStore } from '../../storage/index.js';
import { ti } from '../../i18n/index.js';
import { git, resolveProjectPath } from './git-helpers.js';
export async function handleGenerateChangelog(projectId, specId, format) {
    const projectPath = await resolveProjectPath(projectId);
    const specs = await specStore.listSpecs(projectId);
    const doneSpecs = specs.filter((s) => (specId ? s.id === specId : s.status === 'done'));
    const typeGroups = {
        feature: [],
        bugfix: [],
        refactor: [],
        infra: [],
        docs: [],
        project: [],
    };
    for (const spec of doneSpecs) {
        const entry = `- **[${spec.id}]** ${spec.title}`;
        const group = typeGroups[spec.type];
        if (group) {
            group.push(entry);
        }
    }
    let recentCommits = [];
    try {
        const { stdout } = await git(projectPath, ['log', '--oneline', '--no-decorate', '-20']);
        recentCommits = stdout.trim().split('\n').filter(Boolean);
    }
    catch {
        // ignore
    }
    /* v8 ignore start */
    const now = new Date().toISOString().split('T')[0] ?? new Date().toISOString();
    /* v8 ignore end */
    const changelogContent = format === 'user-facing'
        ? buildUserFacingChangelog(doneSpecs, now)
        : buildTechnicalChangelog(typeGroups, recentCommits, now);
    const changelog = {
        type: 'changelog',
        title: format === 'user-facing' ? 'Release Notes' : 'Changelog',
        path: format === 'user-facing' ? 'RELEASE_NOTES.md' : 'CHANGELOG.md',
        content: changelogContent,
        audience: format === 'user-facing' ? 'end-user' : 'developer',
        sections: [
            {
                title: format === 'user-facing' ? 'Release Notes' : 'Changelog',
                level: 1,
                content: changelogContent,
            },
        ],
        diagrams: [],
        relatedSpecs: doneSpecs.map((s) => s.id),
    };
    const result = {
        action: 'generate-changelog',
        changelog,
        message: ti('tools.manage_git.success', { action: 'generate-changelog' }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
function buildTechnicalChangelog(typeGroups, recentCommits, now) {
    const typeLabels = {
        feature: 'Features',
        bugfix: 'Bug Fixes',
        refactor: 'Refactoring',
        infra: 'Infrastructure',
        docs: 'Documentation',
        project: 'Project',
    };
    const lines = [`# Changelog`, '', `## [Unreleased] - ${now}`, ''];
    for (const [type, entries] of Object.entries(typeGroups)) {
        if (entries.length > 0) {
            /* v8 ignore start */
            lines.push(`### ${typeLabels[type] ?? type}`);
            /* v8 ignore end */
            lines.push('');
            lines.push(...entries);
            lines.push('');
        }
    }
    const unlinkedCommits = recentCommits.filter((c) => !/SPEC-\d{3}/.exec(c));
    if (unlinkedCommits.length > 0) {
        lines.push('### Other Changes');
        lines.push('');
        for (const commit of unlinkedCommits.slice(0, 10)) {
            lines.push(`- ${commit}`);
        }
        lines.push('');
    }
    lines.push('---');
    lines.push('*Generated by Planu SDD*');
    return lines.join('\n');
}
function buildUserFacingChangelog(doneSpecs, now) {
    const lines = [`# Release Notes`, '', `## What's New — ${now}`, ''];
    const features = doneSpecs.filter((s) => s.type === 'feature');
    const bugfixes = doneSpecs.filter((s) => s.type === 'bugfix');
    const improvements = doneSpecs.filter((s) => s.type === 'refactor' || s.type === 'infra');
    if (features.length > 0) {
        lines.push('### New Features');
        lines.push('');
        for (const s of features) {
            lines.push(`- ${s.title}`);
        }
        lines.push('');
    }
    if (bugfixes.length > 0) {
        lines.push('### Bug Fixes');
        lines.push('');
        for (const s of bugfixes) {
            lines.push(`- Fixed: ${s.title}`);
        }
        lines.push('');
    }
    if (improvements.length > 0) {
        lines.push('### Improvements');
        lines.push('');
        for (const s of improvements) {
            lines.push(`- ${s.title}`);
        }
        lines.push('');
    }
    lines.push('---');
    lines.push('*Generated by Planu SDD*');
    return lines.join('\n');
}
//# sourceMappingURL=changelog-ops.js.map