# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR55
# Experiment: ecc scalar multiplication and point order
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR55 | ECC scalar multiplication and point order
# 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

def inv(a,m):
    g,x,_,_=egcd(a%m,m)
    if g!=1: raise ValueError('No inverse: gcd is not 1')
    return x%m

def prime(n):
    return n>=2 and all(n%i for i in range(2,math.isqrt(n)+1))

def on(P,a,b,p):
    return P is None or (isinstance(P,(tuple,list)) and len(P)==2 and all(type(x) is int for x in P) and 0<=P[0]<p and 0<=P[1]<p and (P[1]**2-P[0]**3-a*P[0]-b)%p==0)

def ecadd(P,Q,a,b,p):
    if not prime(p) or p<5 or (4*a**3+27*b*b)%p==0: raise ValueError('Use a nonsingular curve over a prime > 3')
    if not on(P,a,b,p) or not on(Q,a,b,p): raise ValueError('Point not on curve')
    if P is None or Q is None: return Q if P is None else P, {'case':'identity','P':P,'Q':Q}
    x,y=P; u,v=Q
    if x==u and (y+v)%p==0:return None,{'case':'vertical line','P':P,'Q':Q,'result':'infinity'}
    num,den=(3*x*x+a,2*y) if P==Q else (v-y,u-x)
    di=inv(den,p); slope=num*di%p; X=(slope*slope-x-u)%p;Y=(slope*(x-X)-y)%p
    R=(X,Y); assert on(R,a,b,p)
    return R,{'P':P,'Q':Q,'numerator':num%p,'denominator':den%p,'inverse':di,'lambda':slope,'x3':X,'y3':Y}

def ecmul(k,P,a,b,p):
    R=None; steps=[]
    while k:
        bit=k&1
        if bit:R,_=ecadd(R,P,a,b,p)
        steps.append({'bit':bit,'addend':P,'accumulator':R}); P,_=ecadd(P,P,a,b,p);k//=2
    return R,steps

DEFAULT={'p': 17, 'a': 2, 'b': 2, 'P': [5, 1], 'k': 3}
ALTERNATE={'k': 13}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the reference baseline.
    params={**DEFAULT, **(overrides or {})}
    p=params['p']
    a=params['a']
    b=params['b']
    P=params['P']
    k=params['k']
    if not (all(type(x) is int for x in (p,a,b)) and 5<=p<=97 and prime(p) and -997<=a<=997 and -997<=b<=997 and (4*a**3+27*b*b)%p!=0 and type(k) is int and 0<=k<=10000): raise ValueError('Invalid classroom curve or scalar')
    if P is None or not on(P,a,b,p): raise ValueError('Finite on-curve point required')
    P=tuple(P);R,steps=ecmul(k,P,a,b,p);T=None;order=0
    while True:
        T,_=ecadd(T,P,a,b,p);order+=1
        if T is None:break
    if not steps: steps=[{'bit':0,'addend':P,'accumulator':None}]
    result={'point':R,'point_order':order,'valid':on(R,a,b,p)}
    # Independently check the stated mathematical or protocol invariant.
    assert result["valid"] and ecmul(result["point_order"],P,a,b,p)[0] is None, "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))
