// tools/branch-spec.ts — Handler for the branch_spec tool
import { projectDataDir } from '../storage/index.js';
import { readSpecContent } from '../engine/spec-reader.js';
import { createBranch, listBranches, loadBranch, getLatestVersionTag, } from '../engine/spec-versioning/index.js';
export async function handleBranchSpec(args) {
    const { projectId, specId, branchName, fromVersion, specPath } = args;
    const dataDir = projectDataDir(projectId);
    // Check if branch already exists
    const existing = await loadBranch(dataDir, specId, branchName);
    if (existing !== null) {
        const branches = await listBranches(dataDir, specId);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `Branch "${branchName}" already exists for spec ${specId}.`,
                        ``,
                        `Existing branches:`,
                        ...branches.map((b) => `  - ${b.name} (created ${b.createdAt}, from ${b.fromVersion})`),
                    ].join('\n'),
                },
            ],
            isError: true,
        };
    }
    const content = (await readSpecContent(specPath)) ??
        `# ${specId} — branch: ${branchName}\n(content not provided)`;
    const latestTag = fromVersion ?? (await getLatestVersionTag(dataDir, specId)) ?? 'unversioned';
    try {
        const branch = await createBranch(dataDir, {
            projectId,
            specId,
            branchName,
            fromVersion: latestTag,
            content,
        });
        const allBranches = await listBranches(dataDir, specId);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `Branch created successfully.`,
                        ``,
                        `Spec: ${specId}`,
                        `Branch: ${branch.name}`,
                        `Created at: ${branch.createdAt}`,
                        `Based on: ${branch.fromVersion}`,
                        ``,
                        `All branches for this spec (${allBranches.length}):`,
                        ...allBranches.map((b) => `  - ${b.name}`),
                        ``,
                        `To merge back: use merge_spec_branch with branchName="${branchName}"`,
                    ].join('\n'),
                },
            ],
        };
    }
    catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Error: ${msg}` }],
            isError: true,
        };
    }
}
//# sourceMappingURL=branch-spec.js.map