# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR46
# Experiment: rsa encryption and decryption
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR46 | RSA encryption and decryption
# Execute the named operation; expose states and assert the laboratory invariant.
import json

def exptrace(a,e,m):
    # Right-to-left square-and-multiply; reduce after every product.
    if e<0 or m<2: raise ValueError('Require nonnegative exponent and modulus >= 2')
    r=1; b=a%m; steps=[]; i=0
    while e:
        bit=e&1; old=r
        if bit: r=r*b%m
        steps.append({'bit_index':i,'selected':bit,'power_residue':b,'accumulator_before':old,'accumulator':r,'next_square':b*b%m}); b=b*b%m; e//=2; i+=1
    return r,steps

DEFAULT={'m': 7, 'e': 3, 'd': 27, 'n': 55}
ALTERNATE={'m': 12}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    m=params['m']
    e=params['e']
    d=params['d']
    n=params['n']
    if not (all(type(x) is int for x in (m,e,d,n)) and 3<=n<=1000000 and 0<=m<n and 1<=e<=1000000 and 1<=d<=1000000): raise ValueError('Invalid representative or exponent')
    if not 0<=m<n:raise ValueError('representative out of range')
    c,enc=exptrace(m,e,n); recovered,dec=exptrace(c,d,n)
    steps=[dict(s,phase='encrypt') for s in enc]+[dict(s,phase='decrypt') for s in dec];result={'ciphertext':c,'recovered':recovered}
    # Independently check the stated mathematical or protocol invariant.
    if result["recovered"]!=m: raise ValueError("Key pair does not recover the message")
    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))
