// tools/merge-spec-branch.ts — Handler for the merge_spec_branch tool
import { projectDataDir } from '../storage/index.js';
import { mergeBranch } from '../engine/spec-versioning/index.js';
import { diffContents } from '../engine/spec-versioning/differ.js';
import { loadBranch } from '../engine/spec-versioning/brancher.js';
export async function handleMergeSpecBranch(args) {
    const { projectId, specId, branchName, resolvedContent, newVersionTag, message } = args;
    const dataDir = projectDataDir(projectId);
    // Check branch exists before attempting merge
    const branch = await loadBranch(dataDir, specId, branchName);
    if (branch === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: `Error: Branch "${branchName}" not found for spec ${specId}. Create it first with branch_spec.`,
                },
            ],
            isError: true,
        };
    }
    // Compute preview diff before merging
    const mergeContent = resolvedContent ?? branch.content;
    const diff = diffContents(specId, branch.fromVersion, newVersionTag ?? 'merged', branch.content, mergeContent);
    try {
        const result = await mergeBranch(dataDir, {
            projectId,
            specId,
            branchName,
            resolvedContent,
            newVersionTag,
            message,
        });
        if (!result.success) {
            const conflictLines = result.conflicts.flatMap((c) => [
                `  [${c.type}] ${c.description}`,
                ...c.details.map((d) => `    - ${d}`),
            ]);
            return {
                content: [
                    {
                        type: 'text',
                        text: [
                            `Merge failed for branch "${branchName}".`,
                            ``,
                            result.message,
                            result.conflicts.length > 0 ? [``, `Conflicts:`, ...conflictLines].join('\n') : '',
                        ]
                            .filter(Boolean)
                            .join('\n'),
                    },
                ],
                isError: true,
            };
        }
        const acSummary = [
            diff.criteriaChanges.added.length > 0
                ? `  Added AC: ${diff.criteriaChanges.added.length}`
                : null,
            diff.criteriaChanges.removed.length > 0
                ? `  Removed AC: ${diff.criteriaChanges.removed.length}`
                : null,
            diff.criteriaChanges.modified.length > 0
                ? `  Modified AC: ${diff.criteriaChanges.modified.length}`
                : null,
        ].filter((l) => l !== null);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        result.message,
                        ``,
                        `Merge summary:`,
                        `  Spec: ${specId}`,
                        `  Branch: ${branchName} (deleted after merge)`,
                        result.newVersionTag !== undefined ? `  New version: ${result.newVersionTag}` : null,
                        `  Lines added: ${diff.added.length}`,
                        `  Lines removed: ${diff.removed.length}`,
                        acSummary.length > 0 ? `  AC changes:` : null,
                        ...acSummary,
                        diff.sectionChanges.length > 0
                            ? [
                                `  Section changes:`,
                                ...diff.sectionChanges.map((s) => `    - ${s}`),
                            ].join('\n')
                            : null,
                    ]
                        .filter((l) => l !== null)
                        .join('\n'),
                },
            ],
        };
    }
    catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Error: ${msg}` }],
            isError: true,
        };
    }
}
//# sourceMappingURL=merge-spec-branch.js.map