# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR57
# Experiment: ecdh hkdf and authenticated sensor protection
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR57 | ECDH, HKDF and authenticated sensor protection
# Execute the named operation; expose states and assert the laboratory invariant.
import json

def reject(fn):
    try: fn()
    except Exception:return True
    return False

DEFAULT={'message': 'temperature=25.0'}
ALTERNATE={'message': 'temperature=26.0'}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    message=params['message']
    if len(message.encode())>1024: raise ValueError('Maximum 1024 UTF-8 bytes')
    import os
    from cryptography.hazmat.primitives.asymmetric import ec
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    A=ec.generate_private_key(ec.SECP256R1());B=ec.generate_private_key(ec.SECP256R1());s=A.exchange(ec.ECDH(),B.public_key());t=B.exchange(ec.ECDH(),A.public_key());derive=lambda x:HKDF(algorithm=hashes.SHA256(),length=32,salt=None,info=b'PSUT classroom').derive(x);k=derive(s);l=derive(t);nonce=os.urandom(12);c=AESGCM(k).encrypt(nonce,message.encode(),b'device-1')
    steps=[{'stage':'ECDH','shared_match':s==t},{'stage':'HKDF','key_length':len(k)},{'stage':'AEAD','ciphertext_with_tag_bytes':len(c)}];result={'recovered':AESGCM(l).decrypt(nonce,c,b'device-1').decode(),'tamper_rejected':reject(lambda:AESGCM(l).decrypt(nonce,c[:-1]+bytes([c[-1]^1]),b'device-1'))}
    # Independently check the stated mathematical or protocol invariant.
    assert result["recovered"]==message and result["tamper_rejected"], "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))
