# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR83
# Experiment: firewall rule ordering and default policy
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR83 | Firewall rule ordering and default policy
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'port': 443, 'protocol': 'TCP', 'established': False}
ALTERNATE={'port': 23}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    port=params['port']
    protocol=params['protocol']
    established=params['established']
    if type(port) is not int or not 1 <= port <= 65535 or protocol not in ('TCP','UDP') or type(established) is not bool:
        raise ValueError('Invalid classroom input')
    rules=[('established return',established,'ALLOW'),('HTTPS',protocol=='TCP' and port==443,'ALLOW'),('legacy Telnet',protocol=='TCP' and port==23,'DENY')];steps=[];decision='DENY'
    for name,match,action in rules:
        steps.append({'rule':name,'matched':match,'action':action})
        if match:decision=action;break
    else:steps.append({'rule':'default','matched':True,'action':'DENY'})
    result={'decision':decision}
    # Independently check the stated mathematical or protocol invariant.
    assert result["decision"]==("ALLOW" if established or protocol=="TCP" and port==443 else "DENY"), "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))
