// engine/github/gh-cli.ts — Wrapper over GitHub CLI (`gh`) via child_process.execFile.
// All execFile calls are injected for testability.
// ExecFileFn type is defined in src/types/github.ts.
import { execFile as nodeExecFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(nodeExecFile);
const defaultExecFile = async (cmd, args) => {
    return execFileAsync(cmd, args, { maxBuffer: 10 * 1024 * 1024, timeout: 30_000 });
};
/**
 * Check if `gh` CLI is available on the system.
 */
export async function isGhAvailable(exec = defaultExecFile) {
    try {
        await exec('gh', ['--version']);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Run a `gh` CLI command and return parsed JSON output.
 */
export async function ghJson(args, exec = defaultExecFile) {
    const { stdout } = await exec('gh', args);
    return JSON.parse(stdout);
}
/**
 * Run a `gh` CLI command and return raw stdout.
 */
export async function ghRaw(args, exec = defaultExecFile) {
    const { stdout } = await exec('gh', args);
    return stdout.trim();
}
/**
 * Run a `gh auth status` and parse the result.
 */
export async function ghAuthStatus(exec = defaultExecFile) {
    try {
        const { stdout, stderr } = await exec('gh', ['auth', 'status']);
        const output = stdout || stderr;
        const userMatch = /Logged in to .+ as (\S+)/.exec(output);
        const scopeMatch = /Token scopes: (.+)/.exec(output);
        const user = userMatch?.[1];
        const scopes = scopeMatch?.[1]?.split(',').map((s) => s.trim());
        return { authenticated: true, user, scopes };
    }
    catch {
        return { authenticated: false };
    }
}
//# sourceMappingURL=gh-cli.js.map