import { getGitProvider } from '../../git/index.js';
import { getCurrentBranch } from '../../task/index.js';
export function getCommandErrorDetail(error) {
    if (typeof error === 'object' && error !== null && 'stderr' in error) {
        const stderr = error.stderr;
        if (typeof stderr === 'string' && stderr.trim().length > 0) {
            return stderr.trim();
        }
        if (Buffer.isBuffer(stderr)) {
            const text = stderr.toString('utf-8').trim();
            if (text.length > 0) {
                return text;
            }
        }
    }
    return String(error);
}
export function isMergeConflictError(error) {
    const detail = getCommandErrorDetail(error);
    return /\bCONFLICT\b|Automatic merge failed/i.test(detail);
}
export function appendSecondaryError(primary, label, secondary) {
    const secondaryDetail = getCommandErrorDetail(secondary);
    return `${primary} (${label}: ${secondaryDetail})`;
}
export function resolveCurrentBranch(cwd) {
    try {
        const branch = getCurrentBranch(cwd).trim();
        return branch.length > 0 ? { branch } : {};
    }
    catch (error) {
        return { error: getCommandErrorDetail(error) };
    }
}
function requireAvailableProvider(cwd) {
    const provider = getGitProvider();
    const cliStatus = provider.checkCliStatus(cwd);
    if (!cliStatus.available) {
        throw new Error(cliStatus.error);
    }
    return provider;
}
export function fetchExistingPr(cwd, branch) {
    return requireAvailableProvider(cwd).findExistingPr(branch, cwd);
}
export function fetchPrContext(cwd, prNumber) {
    return requireAvailableProvider(cwd).fetchPrReviewComments(prNumber, cwd);
}
export function fetchIssueContext(cwd, issueNumber) {
    return requireAvailableProvider(cwd).fetchIssue(issueNumber, cwd);
}
export function fetchOpenIssueList(cwd) {
    return requireAvailableProvider(cwd).listOpenIssues(cwd);
}
export function fetchOpenPrList(cwd) {
    return requireAvailableProvider(cwd).listOpenPrs(cwd);
}
//# sourceMappingURL=system-git-context.js.map