"""v497 -- CELEST.WP5A.01: WP5a of the research contract CELEST.SEAM.01 -- "the
null ideal from the limit", the first constructive milestone of WP5.  Exact
integer/Fraction arithmetic throughout, no floats.

Question: WP4 (v496) localised the last obstruction between the glue-equivariant
E8[C^2] S-algebra and the (E8)_1 character E4/eta^8: the rational truncation
(the level-2 null ideal deleting 27000 = h_vee^3 out of Sym^2(248)) is NOT in
the jet/loop algebra -- it must be imposed in a boundary/scaling limit (verdict
B(ii), the MMST shape of SEAM.EQUIV.01).  WP5a makes that limit PRECISE and
DERIVES the ideal from root data, in six blocks:

  [E] S1. BASE.  v492/v496 replication: glue dims (60,64,60,64), equivariant
        tower D[d] = 60(d+1)/64(d+1), chi = E4/eta^8 exact through q^6,
        one mu4 period of loop energies sums to 248.
  [E] S2. THE LIMIT AS A REGULARISED FAMILY (epsilon-stabilisation, exact).
        One-parameter family chi_w of graded Fock characters on the CHIRAL
        jet generators (loop energy m = p-q >= 1, radial number r = min(p,q);
        the m = 0, r >= 1 invariant-ring tower carries g_0), generator energy
        E_w = m + w*r in quarter units (u = q^{1/4}).  Exact statements:
        (i) w = 2 IS the chiral jet grading (E_2 = p + q identically;
        generator counts per degree 64,120,128,180,192,240,256,300);
        (ii) STABILISATION THEOREM (coefficientwise): the u^n coefficient of
        chi_w equals the quarter-moded loop Fock for ALL w >= n+1 and is
        STRICTLY larger for every w <= n (verified n <= 8, w <= 10) -- the
        v496 "boundary-limit shadow" is the precise coefficientwise limit
        epsilon = 1/w -> 0 of a family CONTAINING the jet grading (w = 2),
        with explicit threshold w = n+1; (iii) the limit does NOT produce
        the character (u^4 coefficient 897266 >> 248): limit and quotient
        are two separate, honestly typed steps.  Convention clarified:
        897266 is the quarter-moded loop Fock at u^4 = INTEGER level 1
        (v496 S4.5); the integer-moded 248-current Fock counts 248 / 31124
        at levels 1 / 2.
  [E] S3. THE NULL IDEAL DERIVED FROM ROOT DATA (not cited).  In the
        standard 8-coordinate E8 frame (doubled-integer arithmetic, exact):
        Freudenthal multiplicity machinery (unit-tested on the adjoint),
        dominant-weight tally of Sym^2(248) (30876 pairs), and a generic
        character-peeling algorithm DERIVE Sym^2(248) = V(2 theta) + V(omega)
        + V(0) with dims 27000 + 3875 + 1 (Weyl dimension formula, exact
        rationals; independently cross-checked by Weyl-orbit sums); 27000 =
        30^3 = h_vee^3 exactly; C2 = (124, 96, 0), Dynkin indices 6750/750.
        Level-1 integrability: <2 theta, theta_vee> = 4 > 1 and
        <omega, theta_vee> = 2 > 1 -- the only level-1 primary is the vacuum
        ([C] Kac); the maximal submodule of the level-1 vacuum Fock is
        generated by the level-2 singular vector of weight 2 theta ([C] Kac,
        used only through its counting consequence): level-2 quotient
        31124 - 27000 = 4124 = 1 + 248 + 3875 = chi_2 EXACTLY.
  [E] S4. TWO ROUTES, ONE NUMBER.  The mu4 theta-split sector characters
        Theta_Cj/eta^8 (v492 S4 machinery, the boundary/twisted presentation)
        summed at q^2 = (1036,1024,1040,1024) give the SAME 4124: the
        untwisted null-ideal quotient and the mu4-sector lattice sum count
        the same level-2 space; at q^3 the sum is 34752 = chi_3.  Ideal
        bookkeeping beyond level 2 typed [C]: ideal series Fock - chi =
        (0, 0, 27000, 2600000, ...) nonnegative and strictly increasing
        through q^12 (necessary condition for a genuine submodule).
  [E] S5. MMST DICTIONARY (typed rows).  Jet tower <-> pre-limit algebra,
        chi_w family <-> scaling parameter, null ideal <-> maximal ideal,
        one-block locality <-> integer glue weights: all exact counting
        statements computed here; the celestial route now has the SAME
        two-step shape as MMST (limit + maximal ideal), with the ideal
        quantitatively fixed.
  [E] S6. NEGATIVE CONTROLS.  (a) SO(16)_1 through the SAME pipeline (D8
        frame): Sym^2(120) = 5304 + 1820 + 135 + 1 derived (FOUR components
        vs E8's three); 5304 != h_vee(so16)^3 = 14^3 = 2744 -- the h_vee^3
        identity is NOT generic; quotient 7380 - 5304 = 2076 = Theta_D8/eta^8
        at q^2 (independent lattice route: the pipeline is the correct
        general level-1 vacuum recipe, validated on a second algebra); BUT
        the D8 block weights are (0, 1/2, 1, 1) -- h = 1/2 non-integer, the
        four blocks can NOT fuse into one local character (four-block theory)
        vs E8's integer (0,1,1,1) fusing into E4/eta^8: the procedure is not
        trivially projective.  (b) False periodisation: period sums over
        P = 1, 2, 8 quarter-steps give 64, 124, 496 -- only P = 4 = |mu4|
        gives 248.  (c) Swapped glue (60/64 exchanged): the zero-mode anchor
        breaks (D[0] = 64 != 60 = lattice C0 currents).
  [C] Named identifications: "radial decoupling = MMST collar thickness -> 0"
        (the v336/v449 lattice-collar route has the same two-step shape) is
        a named identification, not a computed isomorphism; "the singular
        vector generates the maximal submodule at level 1" is Kac (standard),
        used here only through its counting consequence.
  [O] HONEST LIMIT (the rest of WP5): the limit does NOT generate the
        truncation -- the singular vector as an OPERATOR in the limit net
        stays open (WP5b); the GNS limit state (kernel containing the ideal)
        and local normality / Haag duality of the limit net stay open
        (WP5c/WP5d); convergence topology beyond coefficientwise stays open.
        SEAM.EQUIV.01 stays [O], untouched; no gate closes, no marker moves.

Status: [E] exact stabilisation/derivation/control arithmetic (integer/
Fraction); [C] the named identifications above; [O] the operator question
(WP5b-e).  Python; Wolfram-mirrored (exact peeling decomposition, 4124
two-route checks, period sums), counted per GATE.WOLFRAM.02 convention."""
from fractions import Fraction as F
from itertools import combinations, product
from math import comb, isqrt

from tfpt_constants import check, summary, reset, g_car, N_fam, rankE8

MU4 = 4
H_VEE = 30         # = |Z2| * N_fam * g_car (v495 anchor decomposition)
NMAX = 12          # q-order for integer-moded series
UMAX = 8           # quarter-level cutoff for the chi_w family (= 2 int levels)
WMAX = 10          # largest radial weight w tested in the stabilisation


# ---------------------------------------------------------------------------
# exact integer power series helpers (lists of coefficients, q^0..q^n)
# ---------------------------------------------------------------------------
def series_mul(a, b, nmax):
    out = [0] * (nmax + 1)
    for i, ai in enumerate(a[:nmax + 1]):
        if ai == 0:
            continue
        for j, bj in enumerate(b[:nmax + 1 - i]):
            out[i + j] += ai * bj
    return out


def geom_factor(d, D, nmax):
    """(1 - q^d)^(-D) as a series."""
    out = [0] * (nmax + 1)
    k = 0
    while d * k <= nmax:
        out[d * k] = comb(D + k - 1, k)
        k += 1
    return out


def fock(gen_dims, nmax):
    """prod_d (1 - q^d)^(-gen_dims[d]) over d >= 1."""
    out = [1] + [0] * nmax
    for d, D in gen_dims.items():
        if d == 0 or D == 0:
            continue
        out = series_mul(out, geom_factor(d, D, nmax), nmax)
    return out


def sigma3(n):
    return sum(k ** 3 for k in range(1, n + 1) if n % k == 0)


# ---------------------------------------------------------------------------
# small exact linear algebra (Fractions)
# ---------------------------------------------------------------------------
def solve_fraction(M, b):
    """solve M x = b exactly; M list of int rows, b int vector."""
    n = len(M)
    A = [[F(M[i][j]) for j in range(n)] + [F(b[i])] for i in range(n)]
    for c in range(n):
        p = next(r for r in range(c, n) if A[r][c] != 0)
        A[c], A[p] = A[p], A[c]
        pv = A[c][c]
        A[c] = [x / pv for x in A[c]]
        for r in range(n):
            if r != c and A[r][c] != 0:
                f = A[r][c]
                A[r] = [x - f * y for x, y in zip(A[r], A[c])]
    return [A[i][n] for i in range(n)]


def _det(M):
    """exact determinant of a small integer matrix (Fraction Gauss)."""
    n = len(M)
    A = [[F(M[i][j]) for j in range(n)] for i in range(n)]
    det = F(1)
    for c in range(n):
        p = next((r for r in range(c, n) if A[r][c] != 0), None)
        if p is None:
            return 0
        if p != c:
            A[c], A[p] = A[p], A[c]
            det = -det
        det *= A[c][c]
        pv = A[c][c]
        A[c] = [x / pv for x in A[c]]
        for r in range(c + 1, n):
            if A[r][c] != 0:
                f = A[r][c]
                A[r] = [x - f * y for x, y in zip(A[r], A[c])]
    return det


def ip(a, b):
    return sum(x * y for x, y in zip(a, b))


def vadd(a, b):
    return tuple(x + y for x, y in zip(a, b))


def vsub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def smul(k, a):
    return tuple(k * x for x in a)


# ---------------------------------------------------------------------------
# root-system machinery in DOUBLED integer coordinates (all long roots have
# norm_d = 8; true inner product = ip_d / 4)
# ---------------------------------------------------------------------------
class RootSystem:
    def __init__(self, name, simple, roots):
        self.name = name
        self.simple = [tuple(a) for a in simple]
        self.roots = [tuple(r) for r in roots]
        self.dim = len(simple[0])
        self.n = len(simple)
        assert self.dim == self.n
        # rows of the "columns = simple roots" matrix, for alpha-coordinates
        self.Mrows = [[self.simple[j][i] for j in range(self.n)]
                      for i in range(self.dim)]
        self.cartan = [[ip(a, b) // 4 for b in self.simple]
                       for a in self.simple]
        pos = [r for r in self.roots if self._nonneg_coords(r)]
        assert 2 * len(pos) == len(self.roots)
        self.pos = pos
        s = [0] * self.dim
        for r in pos:
            s = [x + y for x, y in zip(s, r)]
        assert all(x % 2 == 0 for x in s)
        self.rho = tuple(x // 2 for x in s)          # doubled rho
        # fundamental weights (doubled): ip(w_i, alpha_j) = 4 delta_ij
        self.fund = []
        for i in range(self.n):
            b = [4 if j == i else 0 for j in range(self.n)]
            rows = [[self.simple[j][k] for k in range(self.dim)]
                    for j in range(self.n)]
            w = solve_fraction(rows, b)
            assert all(x.denominator == 1 for x in w)
            self.fund.append(tuple(int(x) for x in w))

    def _nonneg_coords(self, v):
        cs = solve_fraction(self.Mrows, list(v))
        return all(c >= 0 for c in cs)

    def alpha_coords(self, v):
        return solve_fraction(self.Mrows, list(v))

    def in_Qplus(self, v):
        cs = self.alpha_coords(v)
        return all(c.denominator == 1 and c >= 0 for c in cs)

    def height(self, v):
        cs = self.alpha_coords(v)
        h = sum(cs)
        assert h.denominator == 1
        return int(h)

    def fold(self, v):
        """dominant Weyl-chamber representative (simple reflections)."""
        v = list(v)
        changed = True
        while changed:
            changed = False
            for a in self.simple:
                c = 0
                for x, y in zip(v, a):
                    c += x * y
                if c < 0:
                    k = c // 4          # ip_d divisible by 4 on the lattice
                    assert c % 4 == 0
                    for t in range(self.dim):
                        v[t] -= k * a[t]
                    changed = True
        return tuple(v)

    def is_dominant(self, v):
        return all(ip(v, a) >= 0 for a in self.simple)

    def weyl_dim(self, lam):
        lr = vadd(lam, self.rho)
        out = F(1)
        for a in self.pos:
            out *= F(ip(lr, a), ip(self.rho, a))
        assert out.denominator == 1
        return int(out)

    def dominant_candidates(self, lam):
        """all dominant weights mu with lam - mu in Q+ (exact enumeration)."""
        nl = ip(lam, lam)
        G = [[ip(wi, wj) for wj in self.fund] for wi in self.fund]
        bounds = [isqrt(nl // G[i][i]) for i in range(self.n)]
        out = []
        for ns in product(*(range(b + 1) for b in bounds)):
            mu = tuple(sum(ns[i] * self.fund[i][k] for i in range(self.n))
                       for k in range(self.dim))
            if ip(mu, mu) <= nl and self.in_Qplus(vsub(lam, mu)):
                out.append(mu)
        return out

    def freudenthal(self, lam):
        """dominant weight multiplicities of V(lam) (exact Freudenthal).

        The k-sum runs over the FULL cone lam - (mu + k a) in Q+ (no early
        break on zero multiplicity -- alpha-strings of non-weights need not
        be contiguous); multiplicities of non-dominant nu are read off via
        Weyl folding.  Alpha-coordinates are precomputed so the cone test
        is a monotone integer comparison."""
        lam = tuple(lam)
        if all(x == 0 for x in lam):
            return {lam: 1}
        cands = sorted(self.dominant_candidates(lam),
                       key=lambda m: self.height(vsub(lam, m)))
        acoords = [(a, [int(c) for c in self.alpha_coords(a)])
                   for a in self.pos]
        mult = {}
        lr = vadd(lam, self.rho)
        nlr = ip(lr, lr)
        for mu in cands:
            if mu == lam:
                mult[lam] = 1
                continue
            cmu = [int(c) for c in self.alpha_coords(vsub(lam, mu))]
            num = 0
            for a, ca in acoords:
                k = 1
                while all(cm - k * c >= 0 for cm, c in zip(cmu, ca)):
                    nu = vadd(mu, smul(k, a))
                    m = mult.get(self.fold(nu), 0)
                    if m:
                        num += m * ip(nu, a)
                    k += 1
            mr = vadd(mu, self.rho)
            den = nlr - ip(mr, mr)
            assert den > 0 and (2 * num) % den == 0
            m_mu = (2 * num) // den
            if m_mu > 0:
                mult[mu] = m_mu
        return mult

    def orbit_size(self, v):
        v = tuple(v)
        seen = {v}
        frontier = [v]
        while frontier:
            nf = []
            for x in frontier:
                for a in self.simple:
                    c = ip(x, a)
                    if c == 0:
                        continue
                    y = tuple(xi - (c // 4) * ai for xi, ai in zip(x, a))
                    if y not in seen:
                        seen.add(y)
                        nf.append(y)
            frontier = nf
        return len(seen)

    def dim_by_orbits(self, mult):
        return sum(m * self.orbit_size(mu) for mu, m in mult.items())


def sym2_dominant_tally(rs, wts):
    """dominant-weight multiplicities of Sym^2 of the weight list.

    Weight multiplicities are Weyl-invariant, so the multiplicity of a
    DOMINANT weight mu equals the number of unordered pairs summing to mu
    itself (no folding -- folding would conflate whole Weyl orbits).
    Returns (tally over dominant weights, total number of pairs)."""
    tal = {}
    n = len(wts)
    npairs = 0
    for i in range(n):
        wi = wts[i]
        for j in range(i, n):
            npairs += 1
            w = tuple(a + b for a, b in zip(wi, wts[j]))
            if rs.is_dominant(w):
                tal[w] = tal.get(w, 0) + 1
    return tal, npairs


def peel(rs, tally):
    """decompose a dominant-multiplicity tally into irreducibles (generic)."""
    residual = dict(tally)
    comps = []
    for _ in range(12):
        support = [mu for mu, v in residual.items() if v != 0]
        if not support:
            break
        assert all(residual[mu] > 0 for mu in support)
        lam = max(support, key=lambda mu: (rs.height(mu), mu))
        mult = residual[lam]
        fm = rs.freudenthal(lam)
        for mu, m in fm.items():
            residual[mu] = residual.get(mu, 0) - mult * m
        comps.append((lam, mult, rs.weyl_dim(lam), fm))
    assert all(v == 0 for v in residual.values())
    return comps


# ---------------------------------------------------------------------------
# frames: standard E8 / D8 (rep theory) and D5+A3 glue frame (v492 arithmetic)
# ---------------------------------------------------------------------------
def e8_std():
    roots = []
    for i, j in combinations(range(8), 2):
        for si in (2, -2):
            for sj in (2, -2):
                v = [0] * 8
                v[i], v[j] = si, sj
                roots.append(tuple(v))
    for signs in product((1, -1), repeat=8):
        if signs.count(-1) % 2 == 0:
            roots.append(tuple(signs))
    simple = [
        (1, -1, -1, -1, -1, -1, -1, 1),      # 1/2(e1+e8-e2-...-e7)
        (2, 2, 0, 0, 0, 0, 0, 0),            # e1+e2
        (-2, 2, 0, 0, 0, 0, 0, 0),           # e2-e1
        (0, -2, 2, 0, 0, 0, 0, 0),           # e3-e2
        (0, 0, -2, 2, 0, 0, 0, 0),           # e4-e3
        (0, 0, 0, -2, 2, 0, 0, 0),           # e5-e4
        (0, 0, 0, 0, -2, 2, 0, 0),           # e6-e5
        (0, 0, 0, 0, 0, -2, 2, 0),           # e7-e6
    ]
    return RootSystem('E8', simple, roots)


def d8_std():
    roots = []
    for i, j in combinations(range(8), 2):
        for si in (2, -2):
            for sj in (2, -2):
                v = [0] * 8
                v[i], v[j] = si, sj
                roots.append(tuple(v))
    simple = [tuple(2 * (1 if k == i else (-1 if k == i + 1 else 0))
                    for k in range(8)) for i in range(7)]
    simple.append((0, 0, 0, 0, 0, 0, 2, 2))     # e7+e8
    return RootSystem('D8', simple, roots)


def build_glue_roots():
    """E8 roots in D5(+)A3 + glue coordinates (v128/v492 construction)."""
    HALF = F(1, 2)
    d5_roots, d5_v = [], []
    for i, j in combinations(range(5), 2):
        for si in (1, -1):
            for sj in (1, -1):
                v = [F(0)] * 5
                v[i], v[j] = F(si), F(sj)
                d5_roots.append(tuple(v))
    for i in range(5):
        for s in (1, -1):
            v = [F(0)] * 5
            v[i] = F(s)
            d5_v.append(tuple(v))
    d5_s, d5_c = [], []
    for signs in product((1, -1), repeat=5):
        v = tuple(HALF * s for s in signs)
        (d5_s if signs.count(-1) % 2 == 0 else d5_c).append(v)
    a3_roots = []
    for i in range(4):
        for j in range(4):
            if i != j:
                v = [F(0)] * 4
                v[i], v[j] = F(1), F(-1)
                a3_roots.append(tuple(v))

    def wclass(k):
        out = []
        for sub in combinations(range(4), k):
            v = [F(-k, 4)] * 4
            for i in sub:
                v[i] += 1
            out.append(tuple(v))
        return out

    z5, z4 = tuple([F(0)] * 5), tuple([F(0)] * 4)
    roots = {}
    for r in d5_roots:
        roots[(r, z4)] = 0
    for r in a3_roots:
        roots[(z5, r)] = 0
    for d in d5_s:
        for w in wclass(1):
            roots[(d, w)] = 1
    for d in d5_v:
        for w in wclass(2):
            roots[(d, w)] = 2
    for d in d5_c:
        for w in wclass(3):
            roots[(d, w)] = 3
    return roots


def monomial_table(dmax):
    """N[d][j] = # monomials z1^p z2^q, p+q = d, with (p-q) mod 4 = j."""
    N = []
    for d in range(dmax + 1):
        row = [0] * 4
        for p in range(d + 1):
            row[(p - (d - p)) % 4] += 1
        N.append(row)
    return N


def d5_coset_norms(maxnorm):
    out = {k: {} for k in ('0', 'v', 's', 'c')}
    for v in product(range(-2, 3), repeat=5):
        n = F(sum(x * x for x in v))
        if n > maxnorm:
            continue
        key = '0' if sum(v) % 2 == 0 else 'v'
        out[key][n] = out[key].get(n, 0) + 1
    rng_half = [F(k, 2) for k in (-3, -1, 1, 3)]
    for v in product(rng_half, repeat=5):
        n = sum(x * x for x in v)
        if n > maxnorm:
            continue
        key = 's' if (sum(v) - F(5, 2)) % 2 == 0 else 'c'
        out[key][n] = out[key].get(n, 0) + 1
    return out


def a3_coset_norms(maxnorm):
    out = {k: {} for k in range(4)}
    for k in range(4):
        shift = F(-k, 4)
        rng = [m + shift for m in range(-3, 4)]
        for v in product(rng, repeat=4):
            if sum(v) != 0:
                continue
            n = sum(x * x for x in v)
            if n > maxnorm:
                continue
            out[k][n] = out[k].get(n, 0) + 1
    return out


# ---------------------------------------------------------------------------
# S1 -- base data + character (v492/v496 replication)
# ---------------------------------------------------------------------------
def section1():
    print("  -- S1: base data (glue dims, tower, character, period)")
    roots = build_glue_roots()
    counts = [sum(1 for c in roots.values() if c == k) for k in range(4)]
    dims = [counts[0] + rankE8] + counts[1:]
    check("S1 [E]: v492 replication -- 240 roots, glue split 52+64+60+64, "
          "dims with Cartan g_j = %s = (60,64,60,64)" % dims,
          len(roots) == 240 and counts == [52, 64, 60, 64]
          and dims == [60, 64, 60, 64])

    N = monomial_table(UMAX)
    D = [sum(dims[j] * N[d][(-j) % 4] for j in range(4))
         for d in range(UMAX + 1)]
    check("S1 [E]: equivariant tower D[d] = 60(d+1)/64(d+1): D[0..6] = %s "
          "(v492/v496 replication)" % D[:7],
          all(D[d] == (60 if d % 2 == 0 else 64) * (d + 1)
              for d in range(UMAX + 1)))

    e4 = [1] + [240 * sigma3(n) for n in range(1, NMAX + 1)]
    eta8inv = fock({n: 8 for n in range(1, NMAX + 1)}, NMAX)
    chi = series_mul(e4, eta8inv, NMAX)
    check("S1 [E]: chi_(E8)_1 = E4/eta^8 = %s (q^0..q^6) exact" % chi[:7],
          chi[:7] == [1, 248, 4124, 34752, 213126, 1057504, 4530744])

    period = sum(dims[n % 4] for n in range(1, 5))
    check("S1 [E]: one mu4 period of loop energies carries (64,60,64,60), "
          "sum = %d = 248 = chi_1 (v496 S4)" % period,
          period == 248 and chi[1] == 248)
    return roots, dims, N, D, chi


# ---------------------------------------------------------------------------
# S2 -- the limit as a regularised family chi_w (exact, coefficientwise)
# ---------------------------------------------------------------------------
def chi_w_gens(w, dims, umax):
    """generator dict energy -> count for the chiral jet family at weight w.

    Chiral generators: loop energy m >= 1, radial number r >= 0 (dim
    g_{(-m) mod 4}), plus the invariant-ring tower m = 0, r >= 1 (dim g_0);
    energy E_w = m + w r in quarter units (u = q^{1/4})."""
    gens = {}
    for m in range(1, umax + 1):
        dimg = dims[(-m) % 4]
        r = 0
        while m + w * r <= umax:
            e = m + w * r
            gens[e] = gens.get(e, 0) + dimg
            r += 1
    r = 1
    while w * r <= umax:
        gens[w * r] = gens.get(w * r, 0) + dims[0]
        r += 1
    return gens


def section2(dims, D, chi):
    print("  -- S2: the boundary limit as an exact epsilon-family chi_w")
    loop = fock({n: dims[(-n) % 4] for n in range(1, UMAX + 1)}, UMAX)
    fam = {w: fock(chi_w_gens(w, dims, UMAX), UMAX)
           for w in range(1, WMAX + 1)}

    print("     table: coefficients of u^n (u = q^(1/4)); rows w, col n")
    hdr = "     w\\n |" + "".join("%12d" % n for n in range(1, UMAX + 1))
    print(hdr)
    for w in (1, 2, 3, 4, 6, 9):
        print("     %3d |" % w
              + "".join("%12d" % fam[w][n] for n in range(1, UMAX + 1)))
    print("     loop|"
          + "".join("%12d" % loop[n] for n in range(1, UMAX + 1)))

    # (i) w = 2 IS the chiral jet grading (E_2 = m + 2r = p + q)
    Dch = []
    for d in range(1, UMAX + 1):
        tot = 0
        for p in range(d + 1):
            q_ = d - p
            if p >= q_:
                tot += dims[(-(p - q_)) % 4]
        Dch.append(tot)
    gens2 = chi_w_gens(2, dims, UMAX)
    check("S2 [E]: w = 2 member IS the chiral jet grading -- generator "
          "counts per degree %s equal the p >= q monomial count (E_2 = "
          "m + 2r = p + q identically)" % Dch,
          all(gens2.get(d, 0) == Dch[d - 1] for d in range(1, UMAX + 1)))

    # (ii) coefficientwise stabilisation: equal iff w >= n+1, strict > else
    ok_stab = True
    for n in range(1, UMAX + 1):
        for w in range(1, WMAX + 1):
            if w >= n + 1:
                ok_stab &= (fam[w][n] == loop[n])
            else:
                ok_stab &= (fam[w][n] > loop[n])
    check("S2 [E]: STABILISATION THEOREM -- coeff of u^n in chi_w equals "
          "the quarter-moded loop Fock for ALL w >= n+1 and is STRICTLY "
          "larger for all w <= n (n <= %d, w <= %d): the v496 boundary "
          "reading is the coefficientwise limit epsilon = 1/w -> 0, with "
          "explicit threshold w = n+1 -- a precise limit of a series, not "
          "a slice" % (UMAX, WMAX), ok_stab)

    # (iii) single-particle content of the limit cycles with period 248
    sp = [dims[(-n) % 4] for n in range(1, 13)]
    per = [sum(sp[4 * k:4 * k + 4]) for k in range(3)]
    check("S2 [E]: limit single-particle spectrum cycles (64,60,64,60); "
          "EVERY mu4 period sums to 248: periods 1..3 = %s" % per,
          per == [248, 248, 248])

    # (iv) convention clarified: u^4 = integer level 1
    check("S2 [E]: CONVENTION -- quarter-moded loop Fock at u^4 (= INTEGER "
          "level 1, v496 S4) counts %d = 897266; at u^8 (= integer level 2) "
          "it counts %d; the limit alone does NOT give the character "
          "(248, 4124): the rational truncation is separate structure"
          % (loop[4], loop[8]),
          loop[4] == 897266 and loop[8] > loop[4] and chi[1] == 248)

    # (v) the FULL jet Fock (both chiralities, v496 S5) for contrast
    f = fock({d: D[d] for d in range(1, UMAX + 1)}, UMAX)
    check("S2 [E]: contrast -- full jet Fock (v496 S5 replication) f = %s "
          "(q^0..q^2 in jet degree): two-sided failure against chi "
          "(128 < 248, 8436 > 4124) as established" % f[:3],
          f[1] == 128 and f[2] == 8436)
    return loop


# ---------------------------------------------------------------------------
# S3 -- the null ideal derived from root data (standard frame, exact)
# ---------------------------------------------------------------------------
def section3(chi):
    print("  -- S3: the null ideal DERIVED (Freudenthal + Weyl + peeling)")
    rs = e8_std()
    check("S3 [E]: standard-frame E8 -- 240 roots (norm 2), 120 positive, "
          "Cartan matrix det = 1, <rho,alpha_i_vee> = 1 for all i",
          len(rs.roots) == 240
          and all(ip(r, r) == 8 for r in rs.roots)
          and len(rs.pos) == 120
          and round(_det(rs.cartan)) == 1
          and all(ip(rs.rho, a) == 4 for a in rs.simple))

    theta = rs.fold(rs.roots[0])
    check("S3 [E]: highest root theta dominant, <theta,rho> = %d = 29 = "
          "h_vee - 1 (h_vee = 30)" % (ip(theta, rs.rho) // 4),
          rs.is_dominant(theta) and ip(theta, rs.rho) // 4 == H_VEE - 1)

    # unit test of the multiplicity machinery on the adjoint
    fm_adj = rs.freudenthal(theta)
    check("S3 [E]: FREUDENTHAL UNIT TEST -- V(theta): zero-weight mult %d = "
          "8 = rank; dim by Weyl formula %d, by orbit sum %d, both = 248"
          % (fm_adj.get((0,) * 8, 0), rs.weyl_dim(theta),
             rs.dim_by_orbits(fm_adj)),
          fm_adj.get((0,) * 8, 0) == 8 and rs.weyl_dim(theta) == 248
          and rs.dim_by_orbits(fm_adj) == 248)

    # Sym^2(248) dominant tally from the 248 weights (240 roots + 8 zeros)
    wts = list(rs.roots) + [(0,) * 8] * 8
    tal, npairs = sym2_dominant_tally(rs, wts)
    two_theta = smul(2, theta)
    check("S3 [E]: Sym^2(248) tally -- %d weight pairs total (= 30876); "
          "zero-weight multiplicity %d = 120 (root pairs {a,-a}) + 36 "
          "(Sym^2 Cartan) = 156; top weight 2*theta has multiplicity %d = 1"
          % (npairs, tal.get((0,) * 8, 0), tal.get(two_theta, 0)),
          npairs == 30876 and tal.get((0,) * 8, 0) == 156
          and tal.get(two_theta, 0) == 1)

    comps = peel(rs, tal)
    dims_found = [c[2] for c in comps]
    mults_found = [c[1] for c in comps]
    print("     derived decomposition of Sym^2(248):")
    for lam, m, d, fm in comps:
        print("       hw (doubled) %s  mult %d  dim %d" % (list(lam), m, d))
    check("S3 [E]: DERIVED (not cited) -- Sym^2(248) = V(2 theta) + "
          "V(omega) + V(0) with dims %s = (27000, 3875, 1), each "
          "multiplicity 1; 27000 = %d^3 = h_vee^3 EXACTLY; the residual of "
          "the peeling is identically zero on every dominant weight"
          % (dims_found, H_VEE),
          len(comps) == 3 and sorted(dims_found, reverse=True)
          == [27000, 3875, 1]
          and mults_found == [1, 1, 1] and comps[0][0] == two_theta
          and 27000 == H_VEE ** 3)

    ok_orb = (rs.dim_by_orbits(comps[0][3]) == 27000
              and rs.dim_by_orbits(comps[1][3]) == 3875)
    check("S3 [E]: ORBIT CROSS-CHECK -- Weyl-orbit sums of the Freudenthal "
          "multiplicities give dim V(2 theta) = %d and dim V(omega) = %d "
          "(independent of the Weyl dimension formula)"
          % (rs.dim_by_orbits(comps[0][3]), rs.dim_by_orbits(comps[1][3])),
          ok_orb)

    omega = comps[1][0]
    c2_2t = ip(two_theta, vadd(two_theta, smul(2, rs.rho))) // 4
    c2_om = ip(omega, vadd(omega, smul(2, rs.rho))) // 4
    c2_adj = ip(theta, vadd(theta, smul(2, rs.rho))) // 4
    x_2t = F(c2_2t * 27000, 2 * 248)
    x_om = F(c2_om * 3875, 2 * 248)
    check("S3 [E]: CASIMIRS (theta^2 = 2 norm) -- C2(adj) = %d = 2 h_vee, "
          "C2(27000) = %d = 124, C2(3875) = %d = 96; Dynkin indices %s, %s "
          "(integers)" % (c2_adj, c2_2t, c2_om, x_2t, x_om),
          c2_adj == 60 and c2_2t == 124 and c2_om == 96
          and x_2t == 6750 and x_om == 750)

    lvl_2t = ip(two_theta, theta) // 4      # <lambda, theta_vee>
    lvl_om = ip(omega, theta) // 4
    check("S3 [E]: LEVEL-1 INTEGRABILITY ([C] Kac criterion, arithmetic "
          "here) -- <2 theta, theta_vee> = %d > 1 and <omega, theta_vee> = "
          "%d > 1: NO nontrivial level-1 primary exists for E8; the 3875 "
          "and 27000 can only enter as descendants resp. null vectors"
          % (lvl_2t, lvl_om), lvl_2t == 4 and lvl_om == 2)

    fockV = fock({n: 248 for n in range(1, NMAX + 1)}, NMAX)
    check("S3 [E]: THE QUOTIENT COUNT -- integer-moded free-current Fock "
          "levels (1, 248, 31124, 2634752); level-2 quotient by the null "
          "ideal V(2 theta): 31124 - 27000 = %d = chi_2 = 4124 = 1 + 248 + "
          "3875 EXACTLY ([C] Kac: the maximal submodule of the level-1 "
          "vacuum Fock is generated by the level-2 singular vector of "
          "weight 2 theta; counting consequence verified)"
          % (fockV[2] - 27000),
          fockV[1] == 248 and fockV[2] == 31124 and fockV[3] == 2634752
          and fockV[2] - 27000 == chi[2] == 4124
          and 4124 == 1 + 248 + 3875)

    ideal = [fockV[n] - chi[n] for n in range(NMAX + 1)]
    check("S3 [C]: IDEAL BOOKKEEPING -- ideal series Fock - chi = %s "
          "(q^0..q^4): zero through level 1, 27000 at level 2, %d at level "
          "3; nonnegative and strictly increasing from level 2 through "
          "q^%d (necessary for a genuine submodule)"
          % (ideal[:5], ideal[3], NMAX),
          ideal[0] == ideal[1] == 0 and ideal[2] == 27000
          and ideal[3] == 2600000
          and all(x >= 0 for x in ideal)
          and all(ideal[n + 1] > ideal[n] for n in range(2, NMAX)))
    return rs, theta


# ---------------------------------------------------------------------------
# S4 -- quotient count = sector-sum count (the two presentations agree)
# ---------------------------------------------------------------------------
def section4(chi):
    print("  -- S4: null-ideal quotient vs mu4 theta-split (two routes)")
    d5 = d5_coset_norms(6)
    a3 = a3_coset_norms(6)
    pairing = {0: ('0', 0), 1: ('s', 1), 2: ('v', 2), 3: ('c', 3)}
    theta_c = {}
    for j, (dk, ak) in pairing.items():
        coeffs = [0] * 4
        for n5, c5 in d5[dk].items():
            for n3, c3v in a3[ak].items():
                n = n5 + n3
                if n <= 6 and n % 2 == 0 and F(n, 2).denominator == 1:
                    coeffs[int(n) // 2] += c5 * c3v
        theta_c[j] = coeffs
    p8 = fock({n: 8 for n in range(1, 4)}, 3)
    sector = {j: series_mul(theta_c[j], p8, 3) for j in range(4)}

    lvl1 = [sector[j][1] for j in range(4)]
    lvl2 = [sector[j][2] for j in range(4)]
    lvl3 = [sector[j][3] for j in range(4)]
    print("     sector characters Theta_Cj/eta^8: q^1 %s, q^2 %s, q^3 %s"
          % (lvl1, lvl2, lvl3))
    check("S4 [E]: sector currents q^1 = %s = (60,64,60,64) (v492 S4)"
          % lvl1, lvl1 == [60, 64, 60, 64])
    check("S4 [E]: TWO ROUTES, ONE NUMBER -- sum of the four sector "
          "characters at q^2 = (1036,1024,1040,1024), total %d = 4124 = "
          "31124 - 27000: the boundary/twisted (lattice theta-split) "
          "presentation and the untwisted null-ideal quotient count the "
          "SAME level-2 space" % sum(lvl2),
          lvl2 == [1036, 1024, 1040, 1024]
          and sum(lvl2) == 4124 == chi[2])
    check("S4 [E]: and at q^3: sum = %d = chi_3 = 34752 (the quotient "
          "route has no independent level-3 count here -- ideal size "
          "2600000 at level 3 is character bookkeeping, honestly typed "
          "[C])" % sum(lvl3), sum(lvl3) == 34752 == chi[3])

    hmin_d5 = [F(0)] + [F(min(n for n in d5[k] if n > 0), 2)
                        for k in ('s', 'v', 'c')]
    hmin_a3 = [F(0)] + [F(min(n for n in a3[k] if n > 0), 2)
                        for k in (1, 2, 3)]
    hdiag = [hmin_d5[j] + hmin_a3[j] for j in range(4)]
    check("S4 [E]: glue-diagonal weights h_j = %s = (0,1,1,1) INTEGER -- "
          "the four sectors fuse into ONE local character (v492 S4/v125 "
          "isotropy); this is what the negative control S6 breaks" % hdiag,
          hdiag == [F(0), F(1), F(1), F(1)])
    return theta_c


# ---------------------------------------------------------------------------
# S5 -- MMST dictionary (typed rows)
# ---------------------------------------------------------------------------
def section5():
    print("  -- S5: the MMST dictionary, honestly typed")
    check("S5 [E]: exact rows of the dictionary -- (i) jet tower "
          "E8[C^2]^mu4 <-> pre-limit algebra: both overcount (897266 vs "
          "248 at level 1 -- computed); (ii) chi_w family <-> scaling "
          "parameter: coefficientwise stabilisation with threshold w = n+1 "
          "(S2 -- computed); (iii) null ideal <-> maximal ideal of the "
          "vacuum Fock: size 27000 = h_vee^3 derived (S3), quotient = "
          "sector sum at level 2 (S4 -- computed); (iv) one-block "
          "locality <-> integer glue weights (0,1,1,1) (S4 -- computed): "
          "the celestial route now has the SAME two-step shape as MMST "
          "(limit + maximal ideal), with the ideal quantitatively fixed",
          True)
    check("S5 [C]: named identifications -- (i) 'radial decoupling = MMST "
          "collar thickness -> 0' is a named identification (the v336/v449 "
          "lattice-collar route has the SAME two-step shape: pre-limit "
          "overcounting algebra, rational net only in the limit), not a "
          "computed isomorphism; (ii) 'singular vector generates the "
          "maximal submodule at level 1' is Kac (standard), used here only "
          "through its counting consequence", True)
    check("S5 [O]: open operator statements (= the rest of WP5) -- "
          "(i) the singular vector as an OPERATOR in the limit net (WP5b), "
          "(ii) does the LIMIT STATE annihilate the ideal (GNS kernel, "
          "WP5c), (iii) local normality / Haag duality of the limit net "
          "(WP5d), (iv) convergence topology beyond coefficientwise: all "
          "OPEN; SEAM.EQUIV.01 untouched, stays [O]", True)


# ---------------------------------------------------------------------------
# S6 -- negative controls
# ---------------------------------------------------------------------------
def section6(dims):
    print("  -- S6: negative controls (the procedure must not be generic)")
    # --- (a) SO(16)_1 start data through the SAME pipeline -----------------
    rs = d8_std()
    check("S6 [E]: D8 frame -- 112 roots, 56 positive, Cartan det = 4, "
          "rho = (7,6,5,4,3,2,1,0) doubled = %s" % (rs.rho,),
          len(rs.roots) == 112 and len(rs.pos) == 56
          and round(_det(rs.cartan)) == 4
          and rs.rho == (14, 12, 10, 8, 6, 4, 2, 0))

    theta8 = rs.fold(rs.roots[0])
    hvee16 = ip(theta8, rs.rho) // 4 + 1
    fm_adj = rs.freudenthal(theta8)
    check("S6 [E]: so(16) unit test -- theta = e1+e2, h_vee = %d = 14; "
          "V(theta): zero-weight mult %d = 8, dim %d = 120 (Weyl = orbit "
          "sum)" % (hvee16, fm_adj.get((0,) * 8, 0), rs.weyl_dim(theta8)),
          hvee16 == 14 and fm_adj.get((0,) * 8, 0) == 8
          and rs.weyl_dim(theta8) == 120
          and rs.dim_by_orbits(fm_adj) == 120)

    wts = list(rs.roots) + [(0,) * 8] * 8
    tal, npairs16 = sym2_dominant_tally(rs, wts)
    comps = peel(rs, tal)
    dims_found = [c[2] for c in comps]
    print("     derived decomposition of Sym^2(120):")
    for lam, m, d, _fm in comps:
        print("       hw (doubled) %s  mult %d  dim %d" % (list(lam), m, d))
    check("S6 [E]: SAME PIPELINE, so(16) -- Sym^2(120) = %s = (5304, 1820, "
          "135, 1), each mult 1, top weight 2 theta: FOUR components (E8 "
          "had three); null ideal dim 5304 != h_vee^3 = %d = 2744: the "
          "27000 = h_vee^3 identity is NOT generic -- it is E8-specific "
          "in this comparison" % (dims_found, 14 ** 3),
          sorted(dims_found, reverse=True) == [5304, 1820, 135, 1]
          and [c[1] for c in comps] == [1, 1, 1, 1]
          and comps[0][0] == smul(2, theta8) and 5304 != 14 ** 3)

    fock16 = fock({n: 120 for n in range(1, 3)}, 2)
    quot16 = fock16[2] - 5304
    # independent lattice count: Theta_D8/eta^8 at q^2
    shells = [0, 0, 0]
    for v in product(range(-2, 3), repeat=8):
        if sum(v) % 2:
            continue
        nn = sum(x * x for x in v)
        if nn <= 4:
            shells[nn // 2] += 1
    p8 = fock({1: 8, 2: 8}, 2)
    vac16 = series_mul(shells, p8, 2)
    check("S6 [E]: so(16)_1 quotient count -- free Fock (1, 120, %d); "
          "level-2 quotient %d - 5304 = %d; INDEPENDENT lattice route "
          "Theta_D8/eta^8 = %s (D8 shells %s = (1,112,1136)): both give "
          "2076 -- the procedure is the correct general level-1 vacuum "
          "recipe, validated on a second algebra"
          % (fock16[2], fock16[2], quot16, vac16, shells),
          fock16 == [1, 120, 7380] and quot16 == 2076
          and shells == [1, 112, 1136] and vac16 == [1, 120, 2076])

    # D8*/D8 coset minimal norms -> conformal weights (0, 1/2, 1, 1)
    min_v = min(sum(x * x for x in v)
                for v in product(range(-2, 3), repeat=8) if sum(v) % 2 == 1)
    halves = [F(k, 2) for k in (-3, -1, 1, 3)]
    min_s, min_c = None, None
    for v in product(halves, repeat=8):
        s = sum(v)
        nn = sum(x * x for x in v)
        if s % 2 == 0:
            min_s = nn if min_s is None or nn < min_s else min_s
        else:
            min_c = nn if min_c is None or nn < min_c else min_c
    h16 = [F(0), F(min_v, 2), F(min_s, 2), F(min_c, 2)]
    check("S6 [E]: THE DISCRIMINATING CONTROL -- so(16)_1 block weights "
          "h = %s = (0, 1/2, 1, 1): h_vector = 1/2 is NOT an integer, so "
          "the four blocks can NOT fuse into one local character -- the "
          "pipeline output stays ONE block of a FOUR-block theory; E8's "
          "glue weights (0,1,1,1) are all integers (S4) and fuse into "
          "the single character E4/eta^8: the procedure is NOT trivially "
          "projective -- it distinguishes the two start data" % h16,
          h16 == [F(0), F(1, 2), F(1), F(1)])

    # --- (b) false periodisation --------------------------------------------
    sums = {P: sum(dims[(-n) % 4] for n in range(1, P + 1))
            for P in (1, 2, 4, 8)}
    check("S6 [E]: FALSE PERIODISATION -- period sums over P quarter-steps: "
          "P=1: %d, P=2: %d, P=4: %d, P=8: %d -- only P = 4 = |mu4| "
          "reproduces the 248 layer (chi_1); Z2 (124) and Z8 (496) fail"
          % (sums[1], sums[2], sums[4], sums[8]),
          sums[1] == 64 and sums[2] == 124 and sums[4] == 248
          and sums[8] == 496)

    # --- (c) swapped glue ----------------------------------------------------
    dims_sw = [64, 60, 64, 60]
    N = monomial_table(2)
    D0_sw = sum(dims_sw[j] * N[0][(-j) % 4] for j in range(4))
    check("S6 [E]: SWAPPED GLUE (60/64 blocks exchanged) -- zero-mode slice "
          "D[0] = %d != 60 = lattice C0-sector current count: the "
          "zero-mode anchor of the bridge breaks (the period sum alone "
          "would still give 248 -- the anchor + theta split carry the "
          "discrimination, honestly noted)" % D0_sw, D0_sw == 64)

    # ideal generators live in the sheet-even subsector (remark-level)
    roots = build_glue_roots()
    classes_2a = sorted(set((2 * c) % 4 for c in roots.values()))
    check("S6 [E]: remark -- the extreme weights 2 alpha of the null ideal "
          "carry glue class 2 j mod 4 in %s = {0,2}: the ideal generator "
          "layer is SHEET-EVEN (the v125 sub-Q-system {0,2} = SO(16)_1 "
          "step)" % classes_2a, classes_2a == [0, 2])


def run():
    reset()
    print("v497  CELEST.WP5A.01: the null ideal from the limit (WP5a of "
          "CELEST.SEAM.01 -- first constructive milestone of WP5)")
    roots, dims, N, D, chi = section1()
    section2(dims, D, chi)
    section3(chi)
    section4(chi)
    section5()
    section6(dims)

    return summary("v497 CELEST.WP5A.01: the v496 boundary-limit shadow made precise -- the "
                   "chi_w family (E_w = m + w r, quarter units) contains the chiral jet "
                   "grading at w = 2 and stabilises coefficientwise to the quarter-moded "
                   "loop Fock at threshold w = n+1 (exact, n <= 8, w <= 10); the limit does "
                   "NOT produce the truncation (897266 >> 248 at level 1) -- but the ideal "
                   "SIZE is DERIVED from root data (Sym^2(248) = 27000 + 3875 + 1 by "
                   "Freudenthal + Weyl + peeling, 27000 = h_vee^3) and the quotient count "
                   "31124 - 27000 = 4124 equals the independent mu4 theta-split sector sum. "
                   "Negative controls: so(16)_1 four blocks, 5304 != 14^3, h = 1/2 breaks "
                   "fusion; only P = |mu4| gives 248. Open (WP5b-e): singular vector as "
                   "operator, GNS limit state, local normality/Haag duality, Costello-Li. "
                   "SEAM.EQUIV.01 untouched")


if __name__ == "__main__":
    raise SystemExit(1 if run() else 0)
