/**
 * olam policy-check — validate PR policies against the current diff.
 *
 * Reads `.olam/policies/*.md` from the workspace root, diffs the current
 * branch against origin/main (or a custom base), and exits non-zero if
 * any error-severity policy is violated.
 *
 *   olam policy-check                     check from cwd against origin/main
 *   olam policy-check --base origin/HEAD  custom base ref
 *   olam policy-check --workspace <path>  custom workspace root
 */
import { execSync } from 'node:child_process';
import pc from 'picocolors';
import { loadPolicies } from '@olam/core/src/policies/loader.js';
import { enforcePolicies } from '@olam/core/src/policies/enforce.js';
function getDiff(base, cwd) {
    // Try `base...HEAD` three-dot diff first; fall back to two-dot diff on failure.
    for (const range of [`${base}...HEAD`, `${base}..HEAD`]) {
        try {
            return execSync(`git diff --name-only ${range}`, {
                cwd,
                encoding: 'utf8',
                stdio: ['pipe', 'pipe', 'pipe'],
            });
        }
        catch {
            // try next
        }
    }
    // Last resort: just list uncommitted changes
    try {
        return execSync('git diff --name-only HEAD', {
            cwd,
            encoding: 'utf8',
            stdio: ['pipe', 'pipe', 'pipe'],
        });
    }
    catch {
        return '';
    }
}
export function registerPolicyCheck(program) {
    program
        .command('policy-check')
        .description('Check .olam/policies/ against the current diff')
        .option('--base <ref>', 'Base git ref to diff against', 'origin/main')
        .option('--workspace <path>', 'Workspace root (defaults to cwd)')
        .action((opts) => {
        const workspaceRoot = opts.workspace ?? process.cwd();
        const policies = loadPolicies(workspaceRoot);
        if (policies.length === 0) {
            console.log(pc.dim('policy-check: no policies found in .olam/policies/ — nothing to enforce'));
            return;
        }
        const diff = getDiff(opts.base, workspaceRoot);
        const results = enforcePolicies(policies, diff);
        let hasErrorFailure = false;
        for (const result of results) {
            if (result.passed)
                continue;
            if (result.severity === 'error') {
                console.error(`${pc.red('policy error')} [${result.policyId}]`);
                console.error(result.message);
                hasErrorFailure = true;
            }
            else {
                console.warn(`${pc.yellow('policy warn')} [${result.policyId}]`);
                console.warn(result.message);
            }
        }
        if (hasErrorFailure) {
            process.exitCode = 1;
        }
    });
}
//# sourceMappingURL=policy-check.js.map