# ============================================================
# CR30 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
from collections import Counter

def row(label,**values): return {'step':label,**values}

# Generate recurrence states and detect the cycle by tracking repeated states.
def lcg(seed,a,c,m,n):
    if not 1<m<=65536 or not 0<a<m or not 0<=c<m or not 0<=seed<m: raise ValueError('Use valid LCG parameters; teaching modulus <=65536')
    x=seed; seen={}; trace=[]; seq=[]
    for i in range(n):
        old=x; x=(a*x+c)%m; seq.append(x); trace.append(row(f'Step {i+1}',previous=old,next=x))
    x=seed
    while x not in seen: seen[x]=len(seen); x=(a*x+c)%m
    return seq,trace,len(seen)-seen[x]

def n(s): return int(s,0)

def pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {}

def run(p):
    count=n(p['count'])
    if not 1<=count<=256: raise ValueError('Count 1–256')
    s,t,period=lcg(n(p['seed']),n(p['a']),n(p['c']),n(p['m']),count);return pack({'sequence':s,'period':period},t+[row('Distribution',counts=dict(sorted(Counter(s).items())),period=period)])

PARAMS = {'seed': '3', 'a': '5', 'c': '1', 'm': '16', 'count': '16'}
EXPECTED = {'sequence': [0, 1, 6, 15, 12, 13, 2, 11, 8, 9, 14, 7, 4, 5, 10, 3], 'period': 16}
ALT = {'seed': '3', 'a': '4', 'c': '1', 'm': '16', 'count': '16'}
ALT_EXPECTED = {'sequence': [13, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], 'period': 1}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR30 synthetic cryptography exercise")
    parser.add_argument("--params", help="JSON parameter override file")
    parser.add_argument("--test", action="store_true")
    args=parser.parse_args()
    if args.test:
        assert run(PARAMS)["result"] == EXPECTED
        assert run(ALT)["result"] == ALT_EXPECTED
        print("CR30 default and changed input passed")
    else:
        parameters=PARAMS if not args.params else {**PARAMS,**json.load(open(args.params))}
        print(json.dumps(run(parameters),indent=2))
