#!/usr/bin/env python3
"""
Standalone verification script for:
  "Structural Obstructions and Radical-Coset Constraints for Balanced 9-Variable
   Boolean Functions with Nonlinearity 242" (IIS-O-0251)

Zero external dependencies (Python 3 standard library only).
Verifies:
  1. All exact Parseval & quadratic-residue bounds for all 13 (2r, wt(Q)) profiles.
  2. Elimination of 5 profiles directly by Parseval + quadratic l1 norm.
  3. Elimination of (2r=4, wt(Q)=128) via RM(3,5) bound h0 >= 4 + mod-3 radical-coset congruence,
     checked both algebraically and by exhaustive enumeration over all 4-var ternary v_L with z+2w <= 3
     for both bent types wt(p)=6 and wt(p)=10.
  4. Exact feasible ranges of d_H(g_0, g_1) in [134, 186] (and [150, 186] for bent Q) and
     RM(3, dim E) lower bounds on h0 via explicit totally singular subspaces E <= Q^{-1}(0).
  5. Exact 512-point FWHT, ANF degree, Walsh spectrum, and autocorrelation comparison between
     Kavut-Yucel's 3-DSBF NL=242 witness and the new O^+(8,2) subgroup (Z_5 x| Z_2) NL=242 witness.
"""
from collections import Counter
import itertools

def fwht(arr):
    res = list(arr)
    n = len(res)
    bit = 1
    while bit < n:
        for i in range(n):
            if not (i & bit):
                u, v = res[i], res[i | bit]
                res[i], res[i | bit] = u + v, u - v
        bit <<= 1
    return res

def anf_degree(bits):
    a = list(bits)
    n = len(a)
    bit = 1
    while bit < n:
        for i in range(n):
            if i & bit:
                a[i] ^= a[i ^ bit]
        bit <<= 1
    return max((i.bit_count() for i, v in enumerate(a) if v), default=0)

def hex_to_bits(h):
    bits = []
    for ch in h.strip():
        v = int(ch, 16)
        bits.extend([(v >> 3) & 1, (v >> 2) & 1, (v >> 1) & 1, v & 1])
    return bits

print("=================================================================")
print("1. VERIFYING POINTWISE IDENTITY ON c=1: 560 - 8y - y^2")
print("=================================================================")
for y in [-28, -12, 4, 20]:
    slack = 560 - 8*y - y*y
    expected = 0 if abs(y) in (20, 28) else 512
    assert slack == expected, f"Mismatch at y={y}: {slack} vs {expected}"
print("  Verified: 560 - 8y - y^2 == 512 * 1_{y in {-12, 4}} on {-28, -12, 4, 20}.")

print("\n=================================================================")
print("2. VERIFYING ALL 13 (2r, wt(Q)) PROFILES & SUBSPACE RM(3, dim E)")
print("=================================================================")
profiles = [
    (0, 0), (0, 128),
    (1, 64), (1, 128), (1, 192),
    (2, 96), (2, 128), (2, 160),
    (3, 112), (3, 128), (3, 144),
    (4, 120), (4, 136),
]

def verify_subspace_min_h0(r, wtQ):
    Q = [0] * 256
    lam = (wtQ == 128 and r > 0)
    is_minus = (r > 0 and wtQ > 128)
    for a in range(256):
        v = 0
        for i in range(r):
            x, y = (a >> (2*i)) & 1, (a >> (2*i + 1)) & 1
            v ^= (x & y)
            if is_minus and i == r - 1:
                v ^= x ^ y
        if lam:
            v ^= (a >> (2*r)) & 1
        elif r == 0 and wtQ == 128:
            v ^= a & 1
        Q[a] = v
    assert sum(Q) == wtQ and Q[0] == 0
    basis = []
    if r == 0:
        basis = [1 << j for j in range(0 if wtQ == 0 else 1, 8)]
    elif not lam and not is_minus:
        basis = [1 << (2*i) for i in range(r)] + [1 << j for j in range(2*r, 8)]
    elif not lam and is_minus:
        basis = [1 << (2*i) for i in range(r - 1)] + [1 << j for j in range(2*r, 8)]
    else:
        basis = [1 << (2*i) for i in range(r)] + [1 << j for j in range(2*r + 1, 8)]
    dimE = len(basis)
    for mask in range(1 << dimE):
        a = 0
        for k in range(dimE):
            if (mask >> k) & 1:
                a ^= basis[k]
        assert Q[a] == 0
    return dimE, 1 << max(0, dimE - 3)

global_d_min, global_d_max = 999, -1
bent_d_min, bent_d_max = 999, -1
killed_direct = []

for r, wtQ in profiles:
    dimE, min_h0 = verify_subspace_min_h0(r, wtQ)
    maxS = 1 << (9 + r)
    step = 1 << (9 - r)
    Lsize = 1 << (2*r)
    minS_basic = 6656 - 40*wtQ + 32 # h0 >= 1
    if minS_basic > maxS:
        killed_direct.append((2*r, wtQ))
        print(f"  2r={2*r}, wt(Q)={wtQ:3d}: KILLED DIRECTLY (minS={minS_basic} > 2^(9+{r})={maxS})")
        continue
    # Enumerate feasible (h0, h2, h13, d, z, w) with h0 >= min_h0
    d_lo, d_hi, cnt = 999, -1, 0
    for h0 in range(min_h0, 256 - wtQ + 1):
        for h2 in range(0, wtQ + 1):
            num_d = 192*16 - 5*wtQ + 4*h0 + 8*h2
            if num_d % 16 != 0: continue
            d = num_d // 16
            if d % 2 != 0 or not (0 <= d <= 256): continue
            for h13 in range(0, 257):
                S = 6656 - 40*wtQ + 32*h0 + 64*(h2 + h13)
                if S > maxS: break
                if S < -maxS or S % step != 0: continue
                z2w = Lsize - S // step
                if not (0 <= z2w <= 2*Lsize): continue
                z_lo = max(0, Lsize - d)
                z_hi = min(Lsize, 256 - d, z2w, 2*Lsize - z2w)
                if z_lo % 2 != z2w % 2: z_lo += 1
                if z_lo <= z_hi:
                    cnt += 1
                    d_lo = min(d_lo, d); d_hi = max(d_hi, d)
    if (2*r, wtQ) != (4, 128):
        global_d_min = min(global_d_min, d_lo)
        global_d_max = max(global_d_max, d_hi)
        if r == 4:
            bent_d_min = min(bent_d_min, d_lo)
            bent_d_max = max(bent_d_max, d_hi)
    tag = " [KILLED NEXT BY MOD-3]" if (2*r, wtQ) == (4, 128) else ""
    print(f"  2r={2*r}, wt(Q)={wtQ:3d}: dimE={dimE}, h0>={min_h0:2d} | {cnt:5d} tuples, d in [{d_lo}, {d_hi}]{tag}")

assert killed_direct == [(0, 0), (0, 128), (2, 64), (2, 128), (4, 96)]
assert (global_d_min, global_d_max) == (134, 186)
assert (bent_d_min, bent_d_max) == (150, 186)
print(f"  Verified: 5 profiles killed directly; universal d_H(g0, g1) in [{global_d_min}, {global_d_max}] (bent Q: [{bent_d_min}, {bent_d_max}]).")

print("\n=================================================================")
print("3. VERIFYING MOD-3 RADICAL-COSET ELIMINATION OF (2r=4, wt(Q)=128)")
print("=================================================================")
# Check both bent types on F_2^4: wt(p)=6 and wt(p)=10
p_plus  = [((x&1)&((x>>1)&1)) ^ (((x>>2)&1)&((x>>3)&1)) for x in range(16)]
p_minus = [p_plus[x] ^ ((x>>2)&1) ^ ((x>>3)&1) for x in range(16)]
assert sum(p_plus) == 6 and sum(p_minus) == 10 and p_plus[0] == 0 and p_minus[0] == 0

for label, p4 in [("type + (wt=6)", p_plus), ("type - (wt=10)", p_minus)]:
    Wp = fwht([1 - 2*b for b in p4])
    eps = [w // 4 for w in Wp]
    assert all(abs(e) == 1 for e in eps)
    base = [-e for e in eps]
    for z2w in range(4):
        min_bad = 999
        for z in range(z2w + 1):
            if (z2w - z) % 2 != 0: continue
            w = (z2w - z) // 2
            for zp in itertools.combinations(range(16), z):
                rem = [i for i in range(16) if i not in zp]
                for wp in itertools.combinations(rem, w):
                    vL = list(base)
                    for i in zp: vL[i] = 0
                    for i in wp: vL[i] = -vL[i]
                    Hv = fwht(vL)
                    Y = [(1 - 2*p4[a]) * Hv[a] for a in range(16)]
                    bad = sum(1 for y in Y if y % 3 != 1)
                    if bad < min_bad: min_bad = bad
        # With h0 >= 4 (from RM(3,5)): 1536 + 32*4 + 64*h13 <= 128*(16 - z2w) => h13 <= 6 - 2*z2w
        max_h13 = (128*(16 - z2w) - 1664) // 64
        assert min_bad > max_h13, f"Failed for {label} z2w={z2w}"
        print(f"  {label}, z+2w={z2w}: forced h1+h3 >= {min_bad:2d} > max allowed {max_h13:2d} -> CONTRADICTION!")
print("  Verified: (2r=4, wt(Q)=128) is IMPOSSIBLE (6 of 13 profiles eliminated in total).")

print("\n=================================================================")
print("4. EXACT 512-POINT FWHT CHECK OF KY 3-DSBF vs NEW O^+(8,2) NL=242")
print("=================================================================")
KY_HEX = (
    "68B7EF2DA03B0D3EA00DB6A96DD99AEAFDB9C842B6D5DC8C4526CE0DD29020DB"
    "B75FE3314568344E73688FF0CB2482E065231869E1AA4583765CC491F8A8DB12"
)
ORTH_HEX = (
    "4EEB9B1EBDD07925217D7598F25606A74F280AD9BD0758E211BE644B7295A774"
    "C0A97BB5797D8889C0E084A131FF39F5717E359F75BE77B4C00B7B1DC228779D"
)
for name, hx in [("Kavut-Yucel 3-DSBF (2010)", KY_HEX), ("New O^+(8,2) Z5x|Z2 (cipher-loom)", ORTH_HEX)]:
    bits = hex_to_bits(hx)
    assert len(bits) == 512
    W = fwht([1 - 2*b for b in bits])
    mx = max(abs(w) for w in W)
    nl = 256 - mx // 2
    assert nl == 242 and mx == 28
    # Autocorrelation via Wiener-Khinchin: AC = FWHT(W^2) / 512
    AC = [v // 512 for v in fwht([w*w for w in W])]
    delta = max(abs(AC[i]) for i in range(1, 512))
    deg = anf_degree(bits)
    abs_spec = sorted(Counter(abs(w) for w in W).items())
    mod8 = sorted(Counter(w % 8 for w in W).items())
    print(f"  {name}:")
    print(f"    wt={sum(bits)}, NL={nl}, max|W|={mx}, deg={deg}, Delta_f={delta}, W(0)={W[0]}")
    print(f"    |W| distribution: {abs_spec}, W mod 8: {mod8}")
print("\nALL CHECKS PASSED!")
