# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR65
# Experiment: file and firmware integrity
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR65 | File and firmware integrity
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import json



DEFAULT={'text': 'FIRMWARE:v1', 'index': 0}
ALTERNATE={'index': 4}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    text=params['text']
    index=params['index']
    if not isinstance(text,str) or not 1<=len(text.encode())<=512 or type(index) is not int or not 0<=index<len(text.encode()): raise ValueError("Byte outside input")
    original=text.encode();modified=bytearray(original);modified[index]^=1;a=hashlib.sha256(original).hexdigest();b=hashlib.sha256(modified).hexdigest();steps=[{'file':'original','length':len(original),'digest':a},{'file':'modified','offset':index,'digest':b}];result={'original_matches':hashlib.sha256(original).hexdigest()==a,'modified_matches':b==a}
    # Independently check the stated mathematical or protocol invariant.
    assert result["original_matches"] and not result["modified_matches"], "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))
