#!/usr/bin/env python3
"""Validate a design-review scorecard against the master it claims to review.

The design stage is the only gate that depends on a judgement made outside the
runner, so it is the only one that can be satisfied by a file describing a
different film. That is not hypothetical: twice in one session a reviewer was
still finishing when the master was re-rendered and then wrote its scorecard over
the new one, leaving a SHIP verdict for a superseded cut sitting exactly where the
gate reads. Both times the two cuts differed by three pack fields — a caption
understating a competitor's cost, a card naming the wrong product tier, and a
verdict card missing its scope. All three would have shipped.

So a verdict is only valid for the bytes it was measured on: the scorecard must
name the master's md5.

Usage:  check_scorecard.py <scorecard.md> <master.mp4>
Exit:   0 SHIP for this master; 1 anything else, with the reason.
"""
import hashlib
import os
import sys


def md5(path):
    h = hashlib.md5()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def main():
    if len(sys.argv) < 3:
        sys.exit("usage: check_scorecard.py <scorecard.md> <master.mp4>")
    sc_path, master = sys.argv[1], sys.argv[2]
    if not os.path.exists(master):
        sys.exit(f"check_scorecard: no master at {master}")
    digest = md5(master)
    if not os.path.exists(sc_path):
        sys.exit(f"check_scorecard: no scorecard at {sc_path} — this master's md5 is {digest}")
    text = open(sc_path, encoding="utf-8", errors="replace").read()

    if digest not in text:
        sys.exit(
            f"check_scorecard: {sc_path} does not name this master's md5.\n"
            f"  master on disk : {digest}\n"
            f"  the scorecard  : reviewed a different cut, or omitted the md5\n"
            f"A verdict is only valid for the file it was measured on. Re-review the\n"
            f"current master (put 'md5 {digest}' on line 1), or delete the scorecard."
        )
    if "VERDICT: FIX-FIRST" in text:
        sys.exit(
            f"check_scorecard: verdict is FIX-FIRST for this master ({digest}).\n"
            f"Apply the P1s in {sc_path} (pack / accents.py / engine), delete the\n"
            f"scorecard, and re-render — a P1 is not a note, it is a blocker."
        )
    if "VERDICT: SHIP" not in text:
        sys.exit(f"check_scorecard: {sc_path} has no VERDICT line (need SHIP or FIX-FIRST)")
    print(f"scorecard OK: VERDICT SHIP for master {digest}")


main()
