# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR40
# Experiment: fermat and euler theorems
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR40 | Fermat and Euler theorems
# Execute the named operation; expose states and assert the laboratory invariant.
import math
import json

def exptrace(a,e,m):
    # Right-to-left square-and-multiply; reduce after every product.
    if e<0 or m<2: raise ValueError('Require nonnegative exponent and modulus >= 2')
    r=1; b=a%m; steps=[]; i=0
    while e:
        bit=e&1; old=r
        if bit: r=r*b%m
        steps.append({'bit_index':i,'selected':bit,'power_residue':b,'accumulator_before':old,'accumulator':r,'next_square':b*b%m}); b=b*b%m; e//=2; i+=1
    return r,steps

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

DEFAULT={'a': 3, 'n': 17}
ALTERNATE={'a': 5, 'n': 55}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    a=params['a']
    n=params['n']
    units=[i for i in range(1,n) if math.gcd(i,n)==1]; phi=len(units)
    y,trace=exptrace(a,phi,n);steps=[{'units':units,'phi':phi,'gcd':math.gcd(a,n)}]+trace
    result={'phi':phi,'residue':y,'condition':math.gcd(a,n)==1,'fermat_applies':prime(n) and a%n!=0}
    # Independently check the stated mathematical or protocol invariant.
    assert not result["condition"] or result["residue"]==1, "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))
