// engine/dora-metrics/git-log.ts — Git log helpers for DORA metrics (SPEC-033)
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
/** Runs git log and returns structured commit entries for the given days */
export async function getCommitLog(projectPath, periodDays) {
    const since = new Date();
    since.setDate(since.getDate() - periodDays);
    try {
        const { stdout } = await execFileAsync('git', ['log', '--all', `--since=${since.toISOString()}`, '--format=%H|%aI|%s', '--no-merges'], { cwd: projectPath, timeout: 30_000 });
        return stdout
            .trim()
            .split('\n')
            .filter(Boolean)
            .map((line) => {
            const parts = line.split('|');
            /* v8 ignore start */
            const hash = parts[0] ?? '';
            /* v8 ignore stop */
            return {
                hash,
                date: parts[1] ?? '',
                subject: parts[2] ?? '',
            };
        });
    }
    catch {
        return [];
    }
}
/** Gets merge commits to main/master/production for deployment frequency */
export async function getMergeCommitsToMain(projectPath, periodDays) {
    const since = new Date();
    since.setDate(since.getDate() - periodDays);
    const mainBranches = ['main', 'master', 'production'];
    const allMerges = [];
    for (const branch of mainBranches) {
        try {
            const { stdout } = await execFileAsync('git', ['log', branch, `--since=${since.toISOString()}`, '--format=%H|%aI|%s', '--first-parent'], { cwd: projectPath, timeout: 30_000 });
            const entries = stdout
                .trim()
                .split('\n')
                .filter(Boolean)
                .map((line) => {
                const parts = line.split('|');
                /* v8 ignore start */
                const hash = parts[0] ?? '';
                /* v8 ignore stop */
                return { hash, date: parts[1] ?? '', subject: parts[2] ?? '' };
            });
            allMerges.push(...entries);
            break;
        }
        catch {
            // Branch doesn't exist, try next
        }
    }
    return allMerges;
}
/**
 * Checks if the repository has enough history for DORA metrics.
 * Returns true if there are commits older than minDays.
 */
export async function hasEnoughHistory(projectPath, minDays = 30) {
    const since = new Date();
    since.setDate(since.getDate() - minDays);
    try {
        const { stdout } = await execFileAsync('git', ['log', '--before', since.toISOString(), '--format=%H', '-1'], { cwd: projectPath, timeout: 10_000 });
        return stdout.trim().length > 0;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=git-log.js.map