# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR85
# Experiment: replay cache sequence and timestamp checks
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR85 | Replay cache, sequence and timestamp checks
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'now': 100, 'timestamp': 98, 'window': 5}
ALTERNATE={'timestamp': 90}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    now=params['now']
    timestamp=params['timestamp']
    window=params['window']
    if any(type(x) is not int or not 0 <= x <= 1000000 for x in (now,timestamp,window)):
        raise ValueError('Invalid classroom input')
    seen=set();steps=[];nonce='classroom-1'
    for attempt in range(2):
        timely=abs(now-timestamp)<=window;fresh=nonce not in seen;accepted=timely and fresh
        if accepted:seen.add(nonce)
        steps.append({'attempt':attempt+1,'age':now-timestamp,'within_window':timely,'nonce_unused':fresh,'accepted':accepted})
    result={'first':steps[0]['accepted'],'second':steps[1]['accepted']}
    # Independently check the stated mathematical or protocol invariant.
    assert result["first"]==(abs(now-timestamp)<=window) and not result["second"], "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))
