# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR38
# Experiment: extended euclidean algorithm three phases
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR38 | Extended Euclidean algorithm: three phases
# 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

DEFAULT={'a': 20, 'n': 23}
ALTERNATE={'a': 421, 'n': 1009}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    a=params['a']
    n=params['n']
    g,x,y,steps=egcd(a,n)
    steps += [{'phase':'Bézout back-substitution coefficients','a':a,'x':x,'n':n,'y':y,'sum':a*x+n*y},{'phase':'reduce and verify','inverse':x%n if g==1 else None,'product_mod_n':a*x%n}]
    result={'gcd':g,'x':x,'y':y,'inverse':x%n if g==1 else None}
    # Independently check the stated mathematical or protocol invariant.
    assert a*result["x"]+n*result["y"]==math.gcd(a,n) and (result["inverse"] is None or a*result["inverse"]%n==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))
