"""Regression gate for an AI judge setup, as declared in protocol-r1.json.

A setup passes on a labelled sample only when its agreement with the experts is at least the expert-to-expert agreement
on all turn-1 pairs minus 5 points; a pairwise setup also needs an order-flip share of at most 20%, and a single-run
rubric setup a rerun change share of at most 20%. Rerun it on every change of judge prompt or model.

Usage: python3 -I -B tools/judge_gate.py <sample1|sample2> [setup ...]
With no setup named it checks every setup and exits 0. With setups named it exits 1 if any of them fails.
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import judgelib as L  # noqa: E402
import samples  # noqa: E402
import score  # noqa: E402


def main():
    tag = sys.argv[1]
    named = sys.argv[2:]
    full = L.expert_agreement(L.load_votes())[0]
    floor = full - 0.05
    res = score.score_sample(tag, samples.draw(int(tag[-1])), floor)
    print(f"{tag}: expert-to-expert agreement {full:.3f}, floor {floor:.3f}")
    failed = []
    for name, g in res["gate"].items():
        if named and name not in named:
            continue
        checks = ", ".join(f"{k} {v[0]} {v[1]} {v[2]}" for k, v in g["checks"].items())
        print(f"{'PASS' if g['pass'] else 'FAIL'} {name}: {checks}")
        if not g["pass"]:
            failed.append(name)
    unknown = [n for n in named if n not in res["gate"]]
    if unknown:
        print(f"unknown setup(s): {unknown}")
        return 2
    if named:
        print(f"VERDICT: {'FAIL' if failed else 'PASS'} {len(named) - len(failed)} of {len(named)} setups pass")
        return 1 if failed else 0
    print(f"VERDICT: {len(res['gate']) - len(failed)} of {len(res['gate'])} setups pass")
    return 0


if __name__ == "__main__":
    sys.exit(main())
