# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR61
# Experiment: truncated hash collision and birthday bound
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR61 | Truncated hash collision and birthday bound
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import json



DEFAULT={'bits': 8}
ALTERNATE={'bits': 12}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    bits=params['bits']
    if type(bits) is not int or not 4<=bits<=16: raise ValueError("Choose 4–16 prefix bits")
    seen={};steps=[]
    for i in range(10000):
        d=int.from_bytes(hashlib.sha256(f'classroom-{i}'.encode()).digest(),'big')>>(256-bits)
        if i<20:steps.append({'sample':i,'digest_prefix':d})
        if d in seen:break
        seen[d]=i
    steps.append({'first':seen[d],'second':i,'prefix':d});result={'samples':i+1,'collision':seen[d]!=i,'prefix_bits':bits}
    # Independently check the stated mathematical or protocol invariant.
    assert result["collision"], "verification failed"
    return {"steps":steps,"result":result}

if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
    if args.test:
        for case in [{},ALTERNATE]:run(case)
        print("PASS")
    else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
