# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR87
# Experiment: kerberos service authenticator and realm trust
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR87 | Kerberos service authenticator and realm trust
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'audience': 'sensor/gateway', 'requested': 'sensor/gateway', 'trusted_realm': True}
ALTERNATE={'requested': 'other/service'}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    audience=params['audience']
    requested=params['requested']
    trusted_realm=params['trusted_realm']
    if type(trusted_realm) is not bool or any(not isinstance(v,str) or not 1<=len(v)<=100 or any(ord(c)<32 for c in v) for v in (audience,requested)):
        raise ValueError('Invalid classroom input')
    seen=set();steps=[]
    for i in range(2):
        auth='client|time100';checks={'audience':audience==requested,'realm_trusted':trusted_realm,'authenticator_unused':auth not in seen};accepted=all(checks.values())
        if accepted:seen.add(auth)
        steps.append({'attempt':i+1,**checks,'accepted':accepted})
    result={'first':steps[0]['accepted'],'replay':steps[1]['accepted']}
    # Independently check the stated mathematical or protocol invariant.
    assert result["first"]==(audience==requested and trusted_realm) 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))
