# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR72
# Experiment: dsa historical signature verification
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR72 | DSA historical signature verification
# 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={'digest': 9}
ALTERNATE={'digest': 10}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    digest=params['digest']
    if type(digest) is not int or not 0<=digest<=10: raise ValueError("Digest representative 0–10")
    p,q,g,y,r,s=23,11,4,18,7,1
    # Generate a fixed classroom fixture from x=3,k=6,H=9, then verify the selected digest.
    x=3;k=6;y=pow(g,x,p);r=pow(g,k,p)%q;s=inv(k,q)*(9+x*r)%q
    w=inv(s,q);u1=digest*w%q;u2=r*w%q;v=(pow(g,u1,p)*pow(y,u2,p)%p)%q;steps=[{'p':p,'q':q,'g':g,'y':y,'r':r,'s':s},{'w':w,'u1':u1,'u2':u2,'v':v}];result={'valid':v==r}
    # Independently check the stated mathematical or protocol invariant.
    assert digest!=9 or result["valid"], "baseline 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))
