# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR62
# Experiment: hash avalanche sensor message
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR62 | Hash avalanche: sensor message
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import json



DEFAULT={'message': 'temperature=25.0', 'bit': 0}
ALTERNATE={'bit': 9}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    message=params['message']
    bit=params['bit']
    if not isinstance(message,str) or not 1<=len(message.encode())<=512 or type(bit) is not int or not 0<=bit<8*len(message.encode()): raise ValueError("Bit outside input")
    m=message.encode();v=bytearray(m);v[bit//8]^=1<<(bit%8);steps=[]
    for alg in ('sha256','sha512','sha3_256'):
        x=hashlib.new(alg,m).digest();y=hashlib.new(alg,v).digest();dist=sum((a^b).bit_count() for a,b in zip(x,y));steps.append({'algorithm':alg,'original':x.hex(),'changed':y.hex(),'distance':dist,'percentage':round(100*dist/(8*len(x)),3)})
    result={'changed_bit':bit,'algorithms':len(steps)}
    # Independently check the stated mathematical or protocol invariant.
    assert all(0<=s["percentage"]<=100 for s in steps), "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))
