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

def egcd(a,b):
    # Track coefficients of a and b alongside the successive remainders.
    r,s,t=a,1,0; nr,ns,nt=b,0,1; steps=[]
    while nr:
        q=r//nr; steps.append({'dividend':r,'divisor':nr,'quotient':q,'remainder':r%nr,'coeff_a':s-q*ns,'coeff_b':t-q*nt})
        r,nr=nr,r-q*nr; s,ns=ns,s-q*ns; t,nt=nt,t-q*nt
    return r,s,t,steps

def inv(a,m):
    g,x,_,_=egcd(a%m,m)
    if g!=1: raise ValueError('No inverse: gcd is not 1')
    return x%m

DEFAULT={'message': 'HI', 'p': 11, 'q': 13, 'e': 7}
ALTERNATE={'message': 'HH'}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    message=params['message']
    p=params['p']
    q=params['q']
    e=params['e']
    if not (all(type(x) is int for x in (p,q,e)) and 3<=p<=997 and 3<=q<=997 and p!=q and all(all(x%j for j in range(2,int(x**0.5)+1)) for x in (p,q)) and 1<e<(p-1)*(q-1) and len(message.encode())<=64): raise ValueError('Invalid RSA parameters or message length')
    n=p*q;d=inv(e,(p-1)*(q-1));steps=[];rec=[]
    for m in message.encode():
        if m>=n:raise ValueError('byte too large for modulus')
        c=pow(m,e,n);r1=pow(c,d%(p-1),p);r2=pow(c,d%(q-1),q);v=(r1*q*inv(q,p)+r2*p*inv(p,q))%n;assert v==pow(c,d,n);rec.append(v);steps.append({'byte':m,'ciphertext':c,'residue_p':r1,'residue_q':r2,'recombined':v})
    if not steps: steps=[{'bytes':0}]
    result={'decoded':bytes(rec).decode(),'d':d,'n':n}
    # Independently check the stated mathematical or protocol invariant.
    assert result["decoded"]==message, "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))
