# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR77
# Experiment: tcp and tls 1 2 handshake sequence
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR77 | TCP and TLS 1.2 handshake sequence
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'certificate_valid': True}
ALTERNATE={'certificate_valid': False}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    certificate_valid=params['certificate_valid']
    if type(certificate_valid) is not bool:
        raise ValueError('Invalid classroom input')
    steps=[{'from':'Client','to':'Server','message':'TCP SYN'},{'from':'Server','to':'Client','message':'TCP SYN-ACK'},{'from':'Client','to':'Server','message':'TCP ACK'},{'from':'Client','to':'Server','message':'ClientHello'},{'from':'Server','to':'Client','message':'ServerHello, Certificate, ServerKeyExchange, ServerHelloDone'},{'state':'verify server certificate and signed ephemeral parameters','valid':certificate_valid}]
    if certificate_valid:steps += [{'from':'Client','to':'Server','message':'ClientKeyExchange, ChangeCipherSpec, Finished'},{'from':'Server','to':'Client','message':'ChangeCipherSpec, Finished'},{'state':'protected application data'}]
    else:steps.append({'state':'fatal alert / abort'})
    result={'application_allowed':certificate_valid}
    # Independently check the stated mathematical or protocol invariant.
    assert result["application_allowed"]==certificate_valid, "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))
