# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR68
# Experiment: authenticated sensor telemetry and replay
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR68 | Authenticated sensor telemetry and replay
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import hmac
import json



DEFAULT={'tamper': False, 'sequence': 1}
ALTERNATE={'tamper': True}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    tamper=params['tamper']
    sequence=params['sequence']
    if type(tamper) is not bool or type(sequence) is not int or not 0<=sequence<=1000000: raise ValueError("Invalid sequence or tamper setting")
    key=b'classroom-key';m=f'device=1;temperature=25.0;seq={sequence}'.encode();tag=hmac.new(key,m,hashlib.sha256).digest();received=m.replace(b'25.0',b'26.0') if tamper else m;last=0;steps=[]
    for i in range(2):
        tag_ok=hmac.compare_digest(tag,hmac.new(key,received,hashlib.sha256).digest());fresh=sequence>last;accepted=tag_ok and fresh
        if accepted:last=sequence
        steps.append({'attempt':i+1,'tag_valid':tag_ok,'fresh':fresh,'accepted':accepted})
    result={'first':steps[0]['accepted'],'replay':steps[1]['accepted']}
    # Independently check the stated mathematical or protocol invariant.
    assert result["first"]== (not tamper and sequence>0) and not result["replay"], "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))
