#!/usr/bin/env python3
"""decoder_start_guard — HF-1166 (night push 129).

Detects the mixed decoder-start-token batch shape behind
transformers #51216: when some rows of a batched encoder-decoder
generation already carry the decoder start token and others do not,
GenerationMixin's batch-level `.all()` check skips prepending for
every row, so the unprefixed rows generate from the wrong decoder
context with no error.

Usage:
    python3 decoder_start_guard.py START_ID row1csv row2csv ...
    e.g. python3 decoder_start_guard.py 2 2,133,138,585 133,2634,2967,10

Prints one line per row (OK / MISSING) and, when any row is missing,
the corrected batch with the start token prepended to exactly the
rows that lack it. Exit code 1 when a row is missing, 0 when clean.
Pure stdlib; rows are token-id lists, no model needed.
"""
import sys


def check_rows(start_id, rows):
    return [bool(r) and r[0] == start_id for r in rows]


def fix_rows(start_id, rows):
    return [list(r) if ok else [start_id] + list(r)
            for r, ok in zip(rows, check_rows(start_id, rows))]


def main(argv):
    if len(argv) < 3:
        print(__doc__)
        return 2
    start_id = int(argv[1])
    rows = [[int(t) for t in a.split(",") if t != ""] for a in argv[2:]]
    ok = check_rows(start_id, rows)
    for i, (r, o) in enumerate(zip(rows, ok)):
        print(f"row {i}: {'OK' if o else 'MISSING start token'} :: {r}")
    if all(ok):
        print("batch clean: every row carries the decoder start token")
        return 0
    print("corrected batch:")
    for r in fix_rows(start_id, rows):
        print(",".join(str(t) for t in r))
    return 1


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