import { isAbsolute, resolve } from 'node:path';
import { runGit } from './branchGitCommands.js';
export function createBranchBaseResolutionCache() {
    return {
        allCandidateRefsByRepositoryKey: new Map(),
        repositoryKeyByGitCwd: new Map(),
    };
}
function resolveRepositoryKey(gitCwd, cache) {
    const cachedKey = cache?.repositoryKeyByGitCwd.get(gitCwd);
    if (cachedKey) {
        return cachedKey;
    }
    const commonDir = runGit(gitCwd, ['rev-parse', '--git-common-dir']);
    const repositoryKey = isAbsolute(commonDir) ? commonDir : resolve(gitCwd, commonDir);
    if (cache) {
        cache.repositoryKeyByGitCwd.set(gitCwd, repositoryKey);
    }
    return repositoryKey;
}
function listAllCandidateRefs(gitCwd, cache) {
    const repositoryKey = resolveRepositoryKey(gitCwd, cache);
    const cachedRefs = cache?.allCandidateRefsByRepositoryKey.get(repositoryKey);
    if (cachedRefs) {
        return cachedRefs;
    }
    const output = runGit(gitCwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes']);
    const refs = output
        .split('\n')
        .map(line => line.trim())
        .filter(line => line.length > 0)
        .filter(ref => !ref.endsWith('/HEAD'));
    const distinctRefs = Array.from(new Set(refs));
    if (cache) {
        cache.allCandidateRefsByRepositoryKey.set(repositoryKey, distinctRefs);
    }
    return distinctRefs;
}
export function listCandidateRefs(gitCwd, branch, cache) {
    return listAllCandidateRefs(gitCwd, cache)
        .filter(ref => ref !== branch)
        .filter(ref => !ref.endsWith(`/${branch}`));
}
//# sourceMappingURL=branchBaseRefCache.js.map