# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR86
# Experiment: kerberos v5 as tgs service ticket dialogue
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR86 | Kerberos V5 AS/TGS/service ticket dialogue
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'now': 100, 'issued': 95, 'lifetime': 10, 'service': 'sensor/gateway'}
ALTERNATE={'now': 110}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    now=params['now']
    issued=params['issued']
    lifetime=params['lifetime']
    service=params['service']
    if any(type(x) is not int or not 0 <= x <= 1000000 for x in (now,issued,lifetime)) or lifetime==0 or not isinstance(service,str) or not 1<=len(service)<=100 or any(ord(c)<32 for c in service):
        raise ValueError('Invalid classroom input')
    valid=issued<=now<issued+lifetime;steps=[{'from':'Client','to':'AS','message':'AS-REQ (preauthentication where required)'},{'from':'AS','to':'Client','message':'AS-REP: TGT + protected session material'},{'from':'Client','to':'TGS','message':'TGS-REQ: TGT + authenticator','ticket_fresh':valid}]
    if valid:steps += [{'from':'TGS','to':'Client','message':'TGS-REP: service ticket + session key','service':service},{'from':'Client','to':'Service','message':'AP-REQ: ticket + authenticator'},{'from':'Service','to':'Client','message':'AP-REP (mutual authentication)'}]
    else:steps.append({'state':'TGT not currently valid; obtain a fresh ticket'})
    result={'service_access':valid,'expires':issued+lifetime}
    # Independently check the stated mathematical or protocol invariant.
    assert result["service_access"]==(issued<=now<issued+lifetime), "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))
