# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR51
# Experiment: elgamal lecture encryption
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR51 | ElGamal lecture encryption
# 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={'q': 19, 'g': 10, 'xa': 5, 'm': 17, 'k': 6}
ALTERNATE={'k': 3}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    q=params['q']
    g=params['g']
    xa=params['xa']
    m=params['m']
    k=params['k']
    if not (all(type(x) is int for x in (q,g,xa,k,m)) and 5<=q<=997 and all(q%i for i in range(2,int(q**0.5)+1)) and 2<=g<q and 1<=xa<=q-2 and 1<=k<=q-2 and 1<=m<q and len({pow(g,i,q) for i in range(q-1)})==q-1): raise ValueError('Invalid prime, generator or private exponent')
    if not 1<=m<q or not 1<=k<q-1:raise ValueError('nonzero message and valid ephemeral exponent required')
    Y=pow(g,xa,q);K=pow(Y,k,q);c1=pow(g,k,q);c2=K*m%q;K2=pow(c1,xa,q);ki=inv(K2,q);recovered=c2*ki%q
    steps=[{'public_key':Y},{'mask':K,'c1':c1,'c2':c2},{'reconstructed_mask':K2,'inverse':ki,'recovered':recovered}];result={'ciphertext':[c1,c2],'recovered':recovered}
    # Independently check the stated mathematical or protocol invariant.
    assert result["recovered"]==m, "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))
