# ============================================================
# CR02 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
def hx(n,w=2): return f'{n:0{w}X}'

# Wrap shifted bits around the fixed word width instead of discarding them.
def rot(x,k,w): return ((x<<k)|(x>>(w-k)))&((1<<w)-1)

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

# Trace left/right halves, rotation and XOR; final swap makes reverse-key decryption possible.
def feistel(p,keys,w=16,shift=4):
    mask=(1<<w)-1; L,R=p>>w,p&mask; trace=[row('Split',L=hx(L,w//4),R=hx(R,w//4))]
    for i,k in enumerate(keys):
        z=rot(R,shift%w,w); f=k^z; old=L; L,R=R,L^f
        trace.append(row(f'Round {i}',key=hx(k,w//4),rotated=hx(z,w//4),F=hx(f,w//4),L=hx(L,w//4),R=hx(R,w//4),xor=f'{hx(old,w//4)} XOR {hx(f,w//4)}'))
    return (R<<w)|L,trace

# Rotate each matrix row while preserving column-major state layout.
def shift(s,inv=False): return bytes(s[4*((i//4+(-1 if inv else 1)*(i%4))%4)+i%4] for i in range(16))

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

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

EXTRA = {}

def run(p):
    p0=int(p['plaintext'],16); keys=[int(x,16) for x in p['keys'].split(',')]; k=n(p['rotation']); bit=n(p['bit'])
    if not 0<=p0<2**32 or not 1<=len(keys)<=16 or any(not 0<=x<65536 for x in keys) or not 0<=k<16 or not 0<=bit<32: raise ValueError('Invalid Feistel input')
    c,t=feistel(p0,keys,shift=k); d,u=feistel(p0^(1<<bit),keys,shift=k)
    r=[row(x['step'],base=x['L']+x['R'],changed=y['L']+y['R'],bits=(int(x['L']+x['R'],16)^int(y['L']+y['R'],16)).bit_count()) for x,y in zip(t,u)]
    return pack({'ciphertext':hx(c,8),'changed':hx(d,8),'bits':(c^d).bit_count()},r)

PARAMS = {'plaintext': 'FACCBF0D', 'keys': '1010,AB2F,4321,2345', 'rotation': '4', 'bit': '0'}
EXPECTED = {'ciphertext': '56C71C1D', 'changed': '57C70C1D', 'bits': 2}
ALT = {'plaintext': 'FACCBF0D', 'keys': '1010,AB2F,4321,2345', 'rotation': '4', 'bit': '7'}
ALT_EXPECTED = {'ciphertext': '56C71C1D', 'changed': 'D6C71C15', 'bits': 2}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR02 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("CR02 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))
