# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR43
# Experiment: chinese remainder theorem
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR43 | Chinese remainder theorem
# 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={'m1': 5, 'm2': 11, 'r1': 2, 'r2': 7}
ALTERNATE={'r2': 3}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    m1=params['m1']
    m2=params['m2']
    r1=params['r1']
    r2=params['r2']
    M=m1*m2;u=inv(m2,m1);v=inv(m1,m2);x=(r1*m2*u+r2*m1*v)%M
    steps=[{'M':M,'M1':m2,'inverse1':u},{'M2':m1,'inverse2':v},{'sum':r1*m2*u+r2*m1*v,'reconstructed':x}];result={'x':x,'residues':[x%m1,x%m2]}
    # Independently check the stated mathematical or protocol invariant.
    assert result["residues"]==[r1%m1,r2%m2], "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))
