# ============================================================
# CR28 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
import time

import statistics

def row(label,**values): return {'step':label,**values}

def n(s): return int(s,0)

def pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {}

def run(p):
    blocks=n(p['blocks']);reps=n(p['repetitions'])
    if not 1<=blocks<=256 or not 1<=reps<=20: raise ValueError('Blocks 1–256, repetitions 1–20')
    properties=[('DES',64,'56','16'),('3DES',64,'112/168 nominal','48'),('AES',128,'128/192/256','10/12/14'),('Blowfish',64,'32–448','16'),('Twofish',128,'128/192/256','16')];t=[row(name,block_bits=bb,key_bits=kb,rounds=r) for name,bb,kb,r in properties]
    return pack({'workload_bytes':blocks*16,'repetitions':reps,'note':'Structural comparison; use separate verified library benchmark cell.'},t)

def library_benchmark(blocks=16,repetitions=5):
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.decrepit.ciphers import algorithms as legacy
    data=bytes(blocks*16); rows=[]
    cases=[('DES via equal-key TDEA',legacy.TripleDES,bytes.fromhex('133457799BBCDFF1')*3),('3DES',legacy.TripleDES,bytes(range(24))),('AES-128',algorithms.AES,bytes(range(16))),('Blowfish',legacy.Blowfish,bytes(range(16)))]
    for name,alg,key in cases:
        try:
            cipher=Cipher(alg(key),modes.ECB()); enc=cipher.encryptor(); ct=enc.update(data)+enc.finalize(); dec=cipher.decryptor(); assert dec.update(ct)+dec.finalize()==data
            et=[];dt=[]
            for _ in range(repetitions):
                start=time.perf_counter_ns();e=cipher.encryptor();e.update(data);e.finalize();et.append((time.perf_counter_ns()-start)/1000)
                start=time.perf_counter_ns();d=cipher.decryptor();d.update(ct);d.finalize();dt.append((time.perf_counter_ns()-start)/1000)
            med=statistics.median(et);rows.append(dict(cipher=name,median_encrypt_us=med,median_decrypt_us=statistics.median(dt),mean_encrypt_us=statistics.mean(et),stdev_encrypt_us=statistics.pstdev(et),throughput_MBps=len(data)/med))
        except Exception as exc: rows.append(dict(cipher=name,status='unavailable: '+str(exc)))
    rows.append(dict(cipher='Twofish',status='not available in selected backend; not benchmarked'))
    return rows

PARAMS = {'blocks': '16', 'repetitions': '5'}
EXPECTED = {'workload_bytes': 256, 'repetitions': 5, 'note': 'Structural comparison; use separate verified library benchmark cell.'}
ALT = {'blocks': '32', 'repetitions': '5'}
ALT_EXPECTED = {'workload_bytes': 512, 'repetitions': 5, 'note': 'Structural comparison; use separate verified library benchmark cell.'}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR28 synthetic cryptography exercise")
    parser.add_argument("--params", help="JSON parameter override file")
    parser.add_argument("--test", action="store_true")
    args=parser.parse_args()
    if args.test:
        assert run(PARAMS)["result"] == EXPECTED
        assert run(ALT)["result"] == ALT_EXPECTED
        print("CR28 default and changed input passed")
    else:
        parameters=PARAMS if not args.params else {**PARAMS,**json.load(open(args.params))}
        print(json.dumps(run(parameters),indent=2))
