// engine/github/auth.ts — Detect available GitHub authentication.
// Priority order: (1) gh CLI auth, (2) GITHUB_TOKEN env var, (3) gitconfig token.
import { ghAuthStatus, isGhAvailable } from './gh-cli.js';
/**
 * Detect the best available GitHub authentication method.
 */
export async function detectAuth(exec, env = process.env) {
    // 1. Check gh CLI
    const ghAvail = await isGhAvailable(exec);
    if (ghAvail) {
        const status = await ghAuthStatus(exec);
        if (status.authenticated) {
            return {
                method: 'gh-cli',
                user: status.user,
                scopes: status.scopes,
            };
        }
    }
    // 2. Check GITHUB_TOKEN env var
    const token = env.GITHUB_TOKEN ?? env.GH_TOKEN;
    if (token) {
        return {
            method: 'env-token',
            message: 'Using GITHUB_TOKEN environment variable.',
        };
    }
    // 3. Check gitconfig (simplified — look for github.token in env or common patterns)
    const gitConfigToken = env.GITHUB_ENTERPRISE_TOKEN ?? env.GH_ENTERPRISE_TOKEN;
    if (gitConfigToken) {
        return {
            method: 'gitconfig',
            message: 'Using token from git configuration.',
        };
    }
    // No auth found
    return {
        method: 'none',
        message: 'No GitHub authentication found. Options:\n' +
            '  1. Install and authenticate GitHub CLI: gh auth login\n' +
            '  2. Set GITHUB_TOKEN environment variable\n' +
            '  3. Configure a token in your .gitconfig',
    };
}
/**
 * Validate that the current auth has the required scopes for an operation.
 */
export function validateScopes(auth, requiredScopes) {
    if (auth.method === 'none') {
        return { valid: false, missing: requiredScopes };
    }
    // If using env token or gitconfig, we cannot verify scopes — assume valid
    if (!auth.scopes || auth.scopes.length === 0) {
        return { valid: true, missing: [] };
    }
    const missing = requiredScopes.filter((s) => !auth.scopes?.includes(s));
    return { valid: missing.length === 0, missing };
}
//# sourceMappingURL=auth.js.map