# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR71
# Experiment: elgamal signature mathematics
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR71 | ElGamal signature mathematics
# 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={'p': 19, 'g': 10, 'x': 5, 'k': 5, 'digest': 7}
ALTERNATE={'digest': 8}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    p=params['p']
    g=params['g']
    x=params['x']
    k=params['k']
    digest=params['digest']
    if not (all(type(z) is int for z in (p,g,x,k,digest)) and 5<=p<=997 and all(p%j for j in range(2,int(p**.5)+1)) and 2<=g<p and len({pow(g,j,p) for j in range(p-1)})==p-1 and 1<=x<=p-2 and 1<=k<=p-2 and 0<=digest<=p-2): raise ValueError("Invalid prime, generator, secret, nonce or digest")
    y=pow(g,x,p);r=pow(g,k,p);s=inv(k,p-1)*(digest-x*r)%(p-1);left=pow(g,digest,p);right=pow(y,r,p)*pow(r,s,p)%p;steps=[{'public':y,'k_inverse':inv(k,p-1)},{'r':r,'s':s},{'left':left,'right':right}];result={'valid':left==right,'altered_rejected':pow(g,digest+1,p)!=right}
    # Independently check the stated mathematical or protocol invariant.
    assert result["valid"] and result["altered_rejected"], "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))
