# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR45
# Experiment: rsa manual key generation
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR45 | RSA manual key generation
# Execute the named operation; expose states and assert the laboratory invariant.
import math
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

def prime(n):
    return n>=2 and all(n%i for i in range(2,math.isqrt(n)+1))

DEFAULT={'p': 5, 'q': 11, 'e': 3}
ALTERNATE={'e': 7}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    p=params['p']
    q=params['q']
    e=params['e']
    if not (type(p) is type(q) is type(e) is int and 3<=p<=997 and 3<=q<=997 and 1<e<(p-1)*(q-1)): raise ValueError('Invalid classroom RSA parameters')
    if p==q or not prime(p) or not prime(q):raise ValueError('distinct primes required')
    n=p*q;phi=(p-1)*(q-1);g,x,y,trace=egcd(e,phi);d=inv(e,phi)
    steps=[{'n':n,'phi':phi,'gcd':g}]+trace+[{'e':e,'d':d,'product_mod_phi':e*d%phi}];result={'public':[e,n],'private':[d,n],'phi':phi}
    # Independently check the stated mathematical or protocol invariant.
    assert result["public"][0]*result["private"][0]%result["phi"]==1, "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))
