import { execFileSync } from 'node:child_process';
import { materializeCloneHeadToRootBranch, relayPushCloneToOrigin, } from '../../task/index.js';
import { getCommandErrorDetail } from './system-git-context.js';
function assertFetchableBranchName(branch) {
    if (branch.startsWith('-')) {
        throw new Error(`Refusing to fetch branch "${branch}" because it starts with "-"`);
    }
}
function buildRemoteTrackingRef(branch) {
    return `refs/remotes/origin/${branch}`;
}
function buildRemoteHeadRef(branch) {
    return `refs/heads/${branch}`;
}
function buildWorktreeBranchRef(branch) {
    return `refs/takt/pr-sync/${branch}`;
}
function runGit(cwd, args) {
    execFileSync('git', args, {
        cwd,
        encoding: 'utf-8',
        stdio: 'pipe',
    });
}
function fetchOriginTrackingRef(projectCwd, branch) {
    assertFetchableBranchName(branch);
    runGit(projectCwd, ['fetch', 'origin', `${buildRemoteHeadRef(branch)}:${buildRemoteTrackingRef(branch)}`]);
}
export function abortMerge(worktreePath) {
    try {
        runGit(worktreePath, ['merge', '--abort']);
        return undefined;
    }
    catch (error) {
        return getCommandErrorDetail(error);
    }
}
export function pushSynced(worktreePath, projectCwd, branch) {
    materializeCloneHeadToRootBranch(worktreePath, projectCwd, branch);
    relayPushCloneToOrigin(worktreePath, projectCwd, branch);
}
export function checkoutWorktreeBranchFromOrigin(projectCwd, worktreePath, branch) {
    const worktreeBranchRef = buildWorktreeBranchRef(branch);
    fetchOriginTrackingRef(projectCwd, branch);
    runGit(worktreePath, ['fetch', projectCwd, `${buildRemoteTrackingRef(branch)}:${worktreeBranchRef}`]);
    runGit(worktreePath, ['checkout', '-B', branch, worktreeBranchRef]);
}
export function fetchRemoteBranch(projectCwd, worktreePath, branch) {
    fetchOriginTrackingRef(projectCwd, branch);
    runGit(worktreePath, ['fetch', projectCwd, `${buildRemoteTrackingRef(branch)}:${buildRemoteTrackingRef(branch)}`]);
}
export function fastForwardPrBranch(cwd, branch) {
    runGit(cwd, ['merge', '--ff-only', buildRemoteTrackingRef(branch)]);
}
export function mergeBaseBranch(cwd, branch) {
    runGit(cwd, ['merge', buildRemoteTrackingRef(branch)]);
}
export function isMergeInProgressError(error) {
    const detail = getCommandErrorDetail(error);
    return detail.includes('MERGE_HEAD exists') || detail.includes('You have not concluded your merge');
}
//# sourceMappingURL=system-effect-git-helpers.js.map