# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR41
# Experiment: repeated squaring and operation counts
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR41 | Repeated squaring and operation counts
# Execute the named operation; expose states and assert the laboratory invariant.
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

DEFAULT={'a': 13, 'e': 27, 'n': 55}
ALTERNATE={'e': 19}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    a=params['a']
    e=params['e']
    n=params['n']
    v,steps=exptrace(a,e,n)
    result={'value':v,'binary_exponent':bin(e),'selected_powers':[2**s['bit_index'] for s in steps if s['selected']],'multiply_count':sum(s['selected'] for s in steps),'square_count':len(steps)}
    # Independently check the stated mathematical or protocol invariant.
    assert result["value"]==pow(a,e,n), "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))
