import { specStore } from '../../storage/index.js';
import { ti } from '../../i18n/index.js';
import { git, resolveProjectPath, slugify, mergeConfig, DEFAULT_BRANCH_PREFIXES, DEFAULT_PROTECTED_BRANCHES, } from './git-helpers.js';
export async function handleCreateBranch(projectId, specId, config) {
    if (!specId) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ error: 'specId is required for create-branch action' }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const projectPath = await resolveProjectPath(projectId);
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [
                { type: 'text', text: JSON.stringify({ error: `Spec '${specId}' not found` }, null, 2) },
            ],
            isError: true,
        };
    }
    const mergedConfig = mergeConfig(config);
    /* v8 ignore start */
    const prefixes = mergedConfig.branchPrefix ?? DEFAULT_BRANCH_PREFIXES;
    const prefix = prefixes[spec.type] ?? 'feat';
    /* v8 ignore end */
    const slug = slugify(spec.title);
    const branchName = `${prefix}/${specId}-${slug}`;
    // Check if branch already exists
    try {
        const { stdout } = await git(projectPath, ['branch', '--list', branchName]);
        if (stdout.trim().length > 0) {
            await git(projectPath, ['checkout', branchName]);
            const result = {
                action: 'create-branch',
                branchName,
                message: `Switched to existing branch '${branchName}'`,
            };
            return {
                content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
            };
        }
    }
    catch {
        // branch list failed — proceed with creation
    }
    await git(projectPath, ['checkout', '-b', branchName]);
    await specStore.updateSpec(projectId, specId, { gitBranch: branchName });
    const result = {
        action: 'create-branch',
        branchName,
        message: ti('tools.manage_git.success', { action: 'create-branch' }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
export async function handleCheckBranch(projectId, _specId, config) {
    const projectPath = await resolveProjectPath(projectId);
    const { stdout: currentBranch } = await git(projectPath, ['rev-parse', '--abbrev-ref', 'HEAD']);
    const branch = currentBranch.trim();
    const mergedConfig = mergeConfig(config);
    /* v8 ignore start */
    const protectedBranches = mergedConfig.protectedBranches ?? DEFAULT_PROTECTED_BRANCHES;
    /* v8 ignore end */
    const isProtected = protectedBranches.includes(branch);
    const conventionPattern = /^(feat|fix|refactor|infra|docs|project)\/SPEC-\d{3}-/;
    const followsConvention = conventionPattern.test(branch);
    const specIdMatch = /SPEC-\d{3}/.exec(branch);
    const branchSpecId = specIdMatch ? specIdMatch[0] : null;
    let specExists = false;
    if (branchSpecId) {
        const spec = await specStore.getSpec(projectId, branchSpecId);
        specExists = spec !== null;
    }
    const issues = [];
    if (isProtected) {
        issues.push(`Currently on protected branch '${branch}'. Create a feature branch for changes.`);
    }
    if (!followsConvention && !isProtected) {
        issues.push(`Branch '${branch}' does not follow Planu naming convention: <type>/SPEC-XXX-<slug>`);
    }
    if (branchSpecId && !specExists) {
        issues.push(`Spec '${branchSpecId}' referenced in branch name not found in project.`);
    }
    const result = {
        action: 'check-branch',
        branchName: branch,
        isProtected,
        followsConvention,
        linkedSpecId: branchSpecId,
        specExists,
        issues,
        message: issues.length === 0
            ? `Branch '${branch}' is valid`
            : `Branch '${branch}' has ${issues.length} issue(s)`,
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
//# sourceMappingURL=branch-ops.js.map