"""RUN-042 - DLMVC's four deep passes on Round 04: constants, cell geometry, phase envelopes, contact skeleton.

The folder of DLMVC (RUN-041) holds four more passes over Round 04, each built on the last, all 2026-09-18/19:
Pass 02 compresses Round 04's error budget with the sharp radius (a tangential Lipschitz bound, an
adjacent-normal outer error eps_deep, an inball perimeter bound, admissible support codewords, a threshold-
adaptive compiler); Pass 03 compiles a support cell into exact polygon geometry and area/perimeter bounds;
Pass 04 sharpens the cell's lower envelope with a 1-Lipschitz phase and builds guaranteed inner cores; Pass 05
writes the fixed-resolution verifier as a finite union of polyhedra and reduces each branch to one quadratic.
Here every constant and sanity number is recomputed, the error bound is tried on random anchored bodies, and
the spike cell the passes share is rebuilt from its support function.

Checks
  A0 anchors      the numbers and formulas below occur in the four passes as written
  W1 budget       Pass 02: its constants at A = Abar and A = 0.8344; eps_deep on random anchored bodies;
                  the adjacency step
  W2 cell         Pass 03: the spike cell - active facets, the area interval, the cell radius; the exact
                  polygon formulas on random codewords
  W3 phase        Pass 04: the phase envelope, the inner core, the three area lower bounds, the sharp cell
                  radius - and the sandwich on the spike body itself
  W4 skeleton     Pass 05: the uniform area signature, signatures on random fans, the dual extreme witnesses,
                  their sparsity, the M = 8 contact basis
  W5 code         the four scripts, read after the rebuild and never run
  P1 package      the four VALIDATION files against the archive, the texts and the numbers recomputed here

Usage: python code/run042_dlmvc_deep_passes.py [--drill] [--blind CID]
"""
import argparse
import copy
import itertools
import json
import math
import re

import mpmath as mp
import numpy as np

import gate
import run007_round04_cover_compiler as r7
from corpus import SOURCES, TREE, source_bytes, walk_sources

FOLDER = "main.zip!/DLMVC_Deep_Lag_Multi_Pass_Verification_Closure_Methodology/"
PASSES = {p: FOLDER + f"AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_{p}_Package_v0.1.zip!/" for p in ("02", "03", "04", "05")}
DOCS = {p: PASSES[p] + f"AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_{p}_v0.1.md" for p in PASSES}
VALS = {p: PASSES[p] + f"AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_{p}_VALIDATION.json" for p in PASSES}
LOG = TREE / "data" / "gate-logs" / "run042-dlmvc-deep-passes.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"

ABAR, L0 = "0.8440935944", "0.8344"
M, Q, R_IN = 128, 5e-4, 0.5
SPIKE = 0.013
GRID = 200000


# ---------------------------------------------------------------- Pass 02: the error budget

def budget(A, M=M, q=Q, r=R_IN):
    """Pass 02's constants for an area cap A, at 30 digits"""
    mp.mp.dps = 30
    A, q, r = mp.mpf(A), mp.mpf(q), mp.mpf(r)
    phi = lambda d: mp.pi * r ** 2 + r * mp.sqrt(d * d - r * r) - r * r * mp.acos(r / d)
    R = mp.findroot(lambda d: phi(d) - A, mp.mpf("0.7"))
    L, D, a = mp.sqrt(R * R - r * r), mp.pi / M, 2 * mp.pi / M
    RP = (R + q) / mp.cos(D)
    e04 = q + (R + RP) * 2 * mp.sin(D / 2)
    deep = (R - r) * (1 / mp.cos(D) - 1) + L * mp.tan(D) + q / mp.cos(D)
    per = 2 * A / r
    V = L * mp.sin(a) + r * (mp.cos(a) - 1)
    quad = 2 * M * (L * (1 - mp.cos(D)) + r * (mp.sin(D) - D))
    rhs = per + quad + 2 * mp.pi * q
    avg = rhs / (2 * mp.pi)
    levels = int(mp.ceil((R - r) / q)) + 2
    step, step_floor = int(mp.ceil((V + q) / q)), int(mp.floor((V + q) / q))
    sum_k = int(mp.floor(M * (avg - r) / q))
    full = M * mp.log10(levels)
    adj = mp.log10(levels) + (M - 1) * mp.log10(2 * step + 1)
    stars = mp.log10(mp.binomial(sum_k + M, M))
    return {"R_sharp": float(R), "L_tangent": float(L), "epsilon_round04_after_radius": float(e04), "beta_round04_after_radius": float(2 * mp.pi * R * e04 + mp.pi * e04 ** 2),
            "epsilon_deep": float(deep), "perimeter_max": float(per), "beta_deep": float(per * deep + mp.pi * deep ** 2), "V_alpha": float(V),
            "adjacent_index_step": step, "adjacent_index_step_floor": step_floor, "support_levels": levels, "quad_error": float(quad),
            "support_sum_rhs": float(rhs), "average_b_max": float(avg), "sum_k_max": sum_k, "local_choices": 2 * step + 1,
            "log10_full_dictionary": float(full), "log10_adjacency_upper": float(adj), "log10_adjacency_ratio": float(adj - full),
            "log10_sum_upper": float(stars), "log10_sum_ratio": float(stars - full)}


def hull_support(points):
    """the support function of conv(B_{1/2}(0) and the points)"""
    P = np.asarray(points, dtype=float)
    return lambda t: np.maximum(R_IN, np.max(np.outer(np.cos(t), P[:, 0]) + np.outer(np.sin(t), P[:, 1]), axis=1))


def eps_trials(R, deep, n=60, seed=42):
    """Pass 02's eps_deep against the actual outer error of Round 04's compiler (RUN-007's polygon, from the
    definition) on random convex bodies between B_{1/2} and B_R: the disk's hull with 1 to 4 points of norm at
    most R"""
    rng = np.random.default_rng(seed)
    ratios = []
    for i in range(n):
        k = 1 + i % 4
        pts = [(rho * math.cos(a), rho * math.sin(a)) for rho, a in zip(rng.uniform(R_IN, R, k), rng.uniform(0, 2 * math.pi, k))]
        h = hull_support(pts)
        P, _, _ = r7.outer_polygon(h, M, Q, r7.up)
        ratios.append(r7.excess(P, h, n=100000) / deep)
    return {"bodies": n, "worst_ratio": float(max(ratios)), "median_ratio": float(np.median(ratios))}


def identities(M=M):
    """Pass 02 G.1's two identities on a fine grid of t in [0, alpha]"""
    a, D = 2 * math.pi / M, math.pi / M
    t = np.linspace(0, a, 10001)
    lam, mu = np.sin(a - t) / np.sin(a), np.sin(t) / np.sin(a)
    x = t - D
    e1 = np.max(np.abs(lam + mu - np.cos(x) / np.cos(D)))
    e2 = np.max(np.abs(lam * t + mu * (a - t) - (D * np.cos(x) / np.cos(D) - x * np.sin(x) / np.sin(D))))
    return {"residuals": [float(e1), float(e2)], "max_at_Delta": bool(np.argmax(lam * t + mu * (a - t)) == 5000)}


# ---------------------------------------------------------------- Pass 03-04: the spike cell

def spike_compute():
    """the cell of U* = conv(B_{1/2}, R_sharp u_phi), phi = 0.013, at M = 128, q = 5e-4: the codeword by
    Round 04's quantization; the active fan (Pass 03 Thm 1, iterated) and the clipped polygon; the exact
    area/perimeter formulas; Pass 03's perimeter/area lower bound and cell radius (t on a fine grid); Pass 04's
    phase envelope, inner core, radial and homothetic bounds and sharp radius (theta on a fine grid); and the
    sandwich checked on U* itself"""
    R = budget(ABAR)["R_sharp"]
    r, a, D = R_IN, 2 * math.pi / M, math.pi / M
    L, ph = math.sqrt(R * R - r * r), math.asin(r / R)
    x = np.array([R * math.cos(SPIKE), R * math.sin(SPIKE)])
    hU = hull_support([x])
    th = a * np.arange(M)
    b = r7.up(hU(th), Q)
    # the active fan by the local redundancy criterion, iterated
    alive = list(range(M))
    changed = True
    while changed:
        changed = False
        for pos in range(len(alive)):
            i, j, k = alive[pos - 1], alive[pos], alive[(pos + 1) % len(alive)]
            ga, gb = (th[j] - th[i]) % (2 * math.pi), (th[k] - th[j]) % (2 * math.pi)
            g = ga + gb
            if b[j] >= math.sin(gb) / math.sin(g) * b[i] + math.sin(ga) / math.sin(g) * b[k] - 1e-15:
                alive.pop(pos)
                changed = True
                break
    # edge lengths on the active fan, the area and perimeter by the formulas and by clipping
    m = len(alive)
    ell = []
    for p in range(m):
        i0, i1, i2 = alive[p - 1], alive[p], alive[(p + 1) % m]
        g0, g1 = (th[i1] - th[i0]) % (2 * math.pi), (th[i2] - th[i1]) % (2 * math.pi)
        ell.append((b[i2] - b[i1] * math.cos(g1)) / math.sin(g1) + (b[i0] - b[i1] * math.cos(g0)) / math.sin(g0))
    area_f = 0.5 * sum(b[i] * l for i, l in zip(alive, ell))
    P, _, _ = r7.outer_polygon(hU, M, Q, r7.up)
    area_c, per_c = r7.shoelace(P), r7.perimeter(P)
    # Pass 03: perimeter / area lower bound
    low = np.maximum(r, b - Q)
    tau = np.minimum(D, np.arcsin(np.minimum(low / R, 1)) - ph)
    I3 = 2 * (r * D + (low - r) * tau - L * (1 - np.cos(tau)) - r * (np.sin(tau) - tau))
    V = lambda t: L * np.sin(t) + r * (np.cos(t) - 1)
    t = np.linspace(0, a, 4001)
    gap, arg = -1.0, None
    for j in range(M):
        H = (np.sin(a - t) * b[j] + np.sin(t) * b[(j + 1) % M]) / math.sin(a)
        Lj = np.maximum(r, np.maximum(low[j] - V(t), low[(j + 1) % M] - V(a - t)))
        k = int(np.argmax(H - Lj))
        if H[k] - Lj[k] > gap:
            gap, arg = float(H[k] - Lj[k]), [j, float(t[k]), float(H[k]), float(Lj[k])]
    # Pass 04: the phase envelope and what follows
    aj = np.arcsin(np.minimum(low / R, 1))
    tau4 = np.minimum(D, aj - ph)
    I4 = 2 * (R * (np.cos(aj - tau4) - np.cos(aj)) + r * (D - tau4))
    def lsharp(theta):
        out = np.full(len(theta), r)
        for j in range(M):
            d = np.abs((theta - th[j] + math.pi) % (2 * math.pi) - math.pi)
            out = np.maximum(out, R * np.sin(np.maximum(ph, aj[j] - d)))
        return out

    def l3(theta):
        """Pass 03's two-sample lower envelope"""
        j = np.floor(theta / a).astype(int) % M
        t = theta - j * a
        return np.maximum(r, np.maximum(low[j] - V(t), low[(j + 1) % M] - V(a - t)))

    hP = lambda theta: r7.support_of(P, theta)

    def extreme(f, sign, n_start=5):
        """the extreme of f over the circle: a grid of GRID angles, then each of the best n_start local extremes
        zoomed four times (20,001 points over +-4 current spacings)"""
        theta = 2 * math.pi * np.arange(GRID) / GRID
        v = sign * f(theta)
        loc = [k for k in range(GRID) if v[k] >= v[k - 1] and v[k] >= v[(k + 1) % GRID]]
        best = None
        for k in sorted(loc, key=lambda k: -v[k])[:n_start]:
            c, span = theta[k], 4 * 2 * math.pi / GRID
            for _ in range(4):
                tt = np.linspace(c - span, c + span, 20001)
                vv = sign * f(tt)
                i = int(np.argmax(vv))
                c, span = tt[i], 4 * (tt[1] - tt[0])
            if best is None or vv[i] > best[1]:
                best = (float(c % (2 * math.pi)), float(vv[i]))
        return best[0], sign * best[1], float(sign * v.max())

    lam_at, lam, lam_grid = extreme(lambda t: lsharp(t) / hP(t), -1)
    rad_at, rad_sharp, rad_grid = extreme(lambda t: hP(t) - lsharp(t), 1)
    r3_at, r3_hp, _ = extreme(lambda t: hP(t) - l3(t), 1)
    Phi = lambda d: math.pi * r * r + r * math.sqrt(max(d * d - r * r, 0)) - r * r * math.acos(min(r / d, 1))
    rad = max(Phi(v) for v in low)
    theta = 2 * math.pi * np.arange(GRID) / GRID
    hu = hU(theta)
    return {"R_sharp": R, "true_area": Phi(R), "active_facets": m, "clipped_edges": int(np.sum(np.hypot(*(np.roll(P, -1, axis=0) - P).T) > 1e-12)),
            "area_formula": float(area_f), "outer_area": float(area_c), "outer_perimeter": float(per_c), "formula_vs_clip": float(abs(area_f - area_c)),
            "cell_perimeter_lower": float(I3.sum()), "cell_area_lower": float(r / 2 * I3.sum()), "cell_radius": gap, "cell_radius_arg": arg,
            "cell_radius_with_hP": [r3_hp, r3_at], "phase_floor": ph, "phase_perimeter_lower": float(I4.sum()), "phase_area_lower": float(r / 2 * I4.sum()),
            "radial_area_lower": rad, "lambda": lam, "lambda_at": lam_at, "lambda_on_grid": lam_grid, "homothetic_area_lower": lam * lam * float(area_c),
            "at_lambda": {"hU": float(hU(np.array([lam_at]))[0]), "hP": float(hP(np.array([lam_at]))[0]), "Lsharp": float(lsharp(np.array([lam_at]))[0])},
            "sharp_cell_radius": rad_sharp, "sharp_cell_radius_at": rad_at, "sharp_cell_radius_on_grid": rad_grid,
            "sandwich": [bool(np.all(lsharp(theta) <= hu + 1e-12)), bool(np.all(hu <= hP(theta) + 1e-12)), bool(np.all(lam * hP(theta) <= hu + 1e-12))]}


def polygon_trials(n=200, seed=43, m=12):
    """Pass 03's exact formulas (edge lengths on the uniform all-active fan; area and perimeter) against clipping,
    on random codewords whose uniform fan is all active"""
    rng = np.random.default_rng(seed)
    a = 2 * math.pi / m
    th = a * np.arange(m)
    worst, used = 0.0, 0
    for _ in range(n):
        b = 0.5 + rng.uniform(0, 0.05, m)
        ell = (np.roll(b, 1) + np.roll(b, -1) - 2 * math.cos(a) * b) / math.sin(a)
        if np.min(ell) <= 0:
            continue
        used += 1
        P = np.array([[-100.0, -100.0], [100.0, -100.0], [100.0, 100.0], [-100.0, 100.0]])
        for t, bb in zip(th, b):
            P = r7.clip(P, np.array([math.cos(t), math.sin(t)]), bb)
        quad = (np.dot(b, np.roll(b, -1)) - math.cos(a) * np.dot(b, b)) / math.sin(a)
        worst = max(worst, abs(quad - r7.shoelace(P)), abs(2 * math.tan(a / 2) * b.sum() - r7.perimeter(P)))
    reg = [float((M * R_IN ** 2 - math.cos(2 * math.pi / M) * M * R_IN ** 2) / math.sin(2 * math.pi / M)), float(M * R_IN ** 2 * math.tan(math.pi / M))]
    return {"codewords": used, "worst": float(worst), "regular": reg}


# ---------------------------------------------------------------- Pass 05: the contact skeleton

def fan_area_matrix(angles):
    """the symmetric matrix of the area quadratic form of the polygon with these (all active) normals: 2A = sum b_i l_i(b)"""
    m = len(angles)
    Lm = np.zeros((m, m))
    for p in range(m):
        g1 = (angles[(p + 1) % m] - angles[p]) % (2 * math.pi)
        g0 = (angles[p] - angles[p - 1]) % (2 * math.pi)
        Lm[p, (p + 1) % m] += 1 / math.sin(g1)
        Lm[p, p] -= math.cos(g1) / math.sin(g1) + math.cos(g0) / math.sin(g0)
        Lm[p, p - 1] += 1 / math.sin(g0)
    return (Lm + Lm.T) / 2


def signature(Hm, tol=1e-9):
    ev = np.linalg.eigvalsh(Hm)
    return [int(np.sum(ev > tol)), int(np.sum(np.abs(ev) <= tol)), int(np.sum(ev < -tol))], ev


def skeleton_compute(seed=44):
    a = 2 * math.pi / M
    sig, ev = signature(fan_area_matrix(a * np.arange(M)))
    closed = [2 * (math.cos(k * a) - math.cos(a)) / math.sin(a) for k in range(M)]
    rng = np.random.default_rng(seed)
    fans = {}
    for m in (5, 7, 10, 16, 32):
        while True:
            angles = np.sort(rng.uniform(0, 2 * math.pi, m))
            gaps = np.diff(np.append(angles, angles[0] + 2 * math.pi))
            if gaps.max() < math.pi * 0.95:
                break
        fans[str(m)] = signature(fan_area_matrix(angles))[0]
    # the translation dual on S = 12 uniform directions: minimal extreme supports
    S = 12
    v = np.array([[math.cos(2 * math.pi * s / S), math.sin(2 * math.pi * s / S)] for s in range(S)])
    pairs = sum(1 for i, j in itertools.combinations(range(S), 2) if np.allclose(v[i] + v[j], 0))
    triples, sparse = 0, 0
    # the support grid shifted half a step from 12 candidate normals: each direction touches two of them
    touch = lambda s: {s % S, (s + 1) % S}
    for i, j, k in itertools.combinations(range(S), 3):
        Mx = np.array([[1.0, 1.0, 1.0], [v[i][0], v[j][0], v[k][0]], [v[i][1], v[j][1], v[k][1]]])
        w = np.linalg.solve(Mx, [1.0, 0.0, 0.0]) if abs(np.linalg.det(Mx)) > 1e-12 else None
        if w is not None and np.all(w > 1e-12):
            triples += 1
            sparse = max(sparse, len(touch(i) | touch(j) | touch(k)))
    # the M = 8 contact basis: floors at 0, 1, 2, 4, 5; the gauges leave b_6 = 1/2 and b_3 = b_7 = x; p = sum b
    s2 = math.sqrt(2)
    lo, hi = 4.0, 3 + s2
    area = lambda p: (lambda x: s2 * (1 + 2 * x) - (1.5 + 2 * x * x))((p - 3) / 2)
    c = np.polyfit([lo, (lo + hi) / 2, hi], [area(lo), area((lo + hi) / 2), area(hi)], 2)
    return {"signature_M128": sig, "zero_modes": [int(k) for k in range(M) if abs(closed[k]) < 1e-12],
            "eigen_extremes": [float(ev.min()), float(ev.max())], "closed_form": float(np.max(np.abs(np.sort(ev) - np.sort(closed)))),
            "random_fans": fans, "dual": [pairs, triples, sparse], "toy": {"interval": [lo, hi], "quadratic": [float(x) for x in c],
                                                                         "minimum": [lo, area(lo)], "exact": [-0.5, 3 + s2, -(6 + 2 * s2), 2 * s2 - 2]}}


# ---------------------------------------------------------------- inputs and world

def load_inputs():
    blobs = {n: source_bytes(n) for n in SOURCES}
    got = {leaf.id: d for leaf, d in walk_sources(blobs, keep=lambda l: any(l.id.startswith(p) for p in PASSES.values())) if d is not None}
    return {"texts": {p: got[DOCS[p]].decode("utf-8") for p in PASSES}, "validations": {p: json.loads(got[VALS[p]]) for p in PASSES},
            "code": {k.split("!/")[-1]: v.decode("utf-8") for k, v in got.items() if k.endswith(".py")},
            "manifest": json.loads(MANIFEST.read_text(encoding="utf-8"))}


def world(inputs):
    b = {"global": budget(ABAR), "threshold": budget(L0)}
    return {**inputs, "budget": b, "trials": eps_trials(b["global"]["R_sharp"], b["global"]["epsilon_deep"]), "identities": identities(),
            "spike": spike_compute(), "polygons": polygon_trials(), "skeleton": skeleton_compute()}


# ---------------------------------------------------------------- checks

ANCHORS = {
    "02": [r"L_\sharp\approx0.519793280754405.", r"\varepsilon^{\mathrm{deep}}_{128,q}\approx0.013327012451412.", r"\operatorname{Per}(U)\le3.3763743776.",
           r"\beta^{\mathrm{deep}}\approx0.045554959320093.", r"D_{128,q}=51.", r"\frac1M\sum_jb_j\le0.544194977076031.", r"R(L_0)\approx0.693830648713341.",
           r"\varepsilon^{\mathrm{deep}}(L_0)\approx0.012367453525630,", r"\beta^{\mathrm{deep}}(L_0)\approx0.041758131756797,",
           r"\varepsilon^{\mathrm{deep}}_{M,q}=(R-r)(\sec\Delta-1)+\sqrt{R^2-r^2}\tan\Delta+q\sec\Delta."],
    "03": [r"\text{activefacets}=103.", r"A^+_{\mathrm{cell}}\approx0.846661292560715.", r"A^-_{\mathrm{cell}}\approx0.841460223264416.",
           r"\varepsilon_{\mathrm{cell}}\approx0.013316971063423,", r"A_{\mathrm{quad}}=0.785555907485606."],
    "04": [r"A^-_{\mathrm{phase}}\approx0.842616436112934.", r"A^-_{\mathrm{rad}}\approx0.844007644444885.", r"A^-_{\mathrm{hom}}\approx0.826806954784855.",
           r"\varepsilon_{\mathrm{cell}}\approx0.013060516377839.", r"\varepsilon^\sharp_{\mathrm{cell}}\approx0.005967703749722.",
           r"\lambda_{\mathbfb}\approx0.988205366260544."],
    "05": [r"(+,\0,\0,\-^{125}).", r"\boxed{6}$$個2-activeantipodalwitnesses", r"\boxed{40}$$個genuine3-activeorigin-enclosingwitnesses",
           r"p\in[4.000000000000000,4.414213562373095].", r"A_{\min}\approx0.828427124746190"],
}

CLAIMS = {
    "budget_claim": {"disagree": {"global": [], "threshold": []}, "trials": {"bodies": 60, "worst_ratio": 0.631, "median_ratio": 0.351},
                     "identities": [True, True, True], "step": [51, 50, 48, 47], "reduction": 0.8402},
    "cell_claim": {"facets": [103, 103], "formula_vs_clip": True, "outer": [0.846661292560721, 3.3771690420862], "lower": [3.36584089305767, 0.841460223264417],
                   "radius": [0.013317, 0, 0.02503], "radius_with_hP": 0.0130615798, "uniform": [200, True], "regular": 8e-15},
    "phase_claim": {"floor": 0.765991489296295, "lower": [0.842616436112935, 0.844007644444885, 0.826801748731], "lambda": [0.9882022551, 0.8176473, False],
                    "recorded_core_there": [1.6e-06, 8e-05], "sharp_radius": [0.00596929668962, 0.8176473, False], "bracket": True, "sandwich": [True, True, True]},
    "skeleton_claim": {"signature_M128": [1, 2, 125], "zero_modes": [1, 127], "extremes": [-81.470968, 0.049097244], "closed_form": True,
                       "random_fans": {"5": [1, 2, 2], "7": [1, 2, 4], "10": [1, 2, 7], "16": [1, 2, 13], "32": [1, 2, 29]}, "dual": [6, 40, 6],
                       "toy": [4.0, 4.41421356237309, True, 0.82842712474619]},
    "code_facts": {"lines": {"AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_02_constants.py": 114, "AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_03_cell_geometry.py": 123,
                             "AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_04_phase_core.py": 113, "AMRAL_LUC_FC_Verification_Round_04_Deep_Audit_Pass_05_contact_skeleton.py": 46},
                   "prints_the_replay_block": {"02": True, "03": True, "04": True, "05": True}, "step_by_ceiling": True, "unguarded_quantization": True, "grid": ["240000"],
                   "closed_form_spectrum": True,
                   "unshipped": ["pass03_cell_radius", "pass04_phase_bound", "pass04_quote_of_pass03", "pass05_eigen_extremes", "pass05_toy"]},
}


def a0_anchors(w):
    return [f"Pass {p}: anchor not found: {a[:50]}" for p, frags in ANCHORS.items() for a in frags if a not in gate.squash(w["texts"][p])]


def sig(x, n=4):
    return float(f"{x:.{n - 1}e}")


def close(a, b, tol):
    return abs(a - b) <= tol * max(1.0, abs(b))


def w1_budget(w):
    """Pass 02: every constant its VALIDATION records, at both caps, recomputed; eps_deep against the actual outer
    error on 60 random anchored bodies; the two identities; the adjacency step, which the strict quantization
    error would let fall by one"""
    out, B, v = [], w["budget"], w["validations"]["02"]["constants"]
    keys = [k for k in v["global_upper_cap_example"] if k not in ("A", "r", "M", "q")]
    agree = {name: [k for k in keys if not (close(B[name][k], v[ex][k], 1e-12) if isinstance(v[ex][k], float) else B[name][k] == v[ex][k])]
             for name, ex in (("global", "global_upper_cap_example"), ("threshold", "threshold_0_8344_example"))}
    got = {"disagree": agree, "trials": {k: sig(x, 3) if isinstance(x, float) else x for k, x in w["trials"].items()},
           "identities": [x < 1e-12 for x in w["identities"]["residuals"]] + [w["identities"]["max_at_Delta"]],
           "step": [B["global"]["adjacent_index_step"], B["global"]["adjacent_index_step_floor"], B["threshold"]["adjacent_index_step"],
                    B["threshold"]["adjacent_index_step_floor"]], "reduction": round(1 - B["global"]["epsilon_deep"] / 0.08339137281575232, 4)}
    if any(agree.values()) or w["trials"]["worst_ratio"] > 1 or not all(got["identities"]) or got != w["budget_claim"]:
        out.append(f"Pass 02's budget: {got}")
    w["w1"] = got
    return out


def w2_cell(w):
    """Pass 03: the spike cell rebuilt - active facets by its redundancy criterion and by clipping, the exact
    area formula against the clipped polygon, the area interval, the cell radius and where it is attained; the
    uniform formulas on random codewords; the regular polygon"""
    out, s, p = [], w["spike"], w["polygons"]
    got = {"facets": [s["active_facets"], s["clipped_edges"]], "formula_vs_clip": s["formula_vs_clip"] < 1e-13, "outer": [sig(s["outer_area"], 15), sig(s["outer_perimeter"], 15)],
           "lower": [sig(s["cell_perimeter_lower"], 15), sig(s["cell_area_lower"], 15)], "radius": [sig(s["cell_radius"], 6), s["cell_radius_arg"][0], sig(s["cell_radius_arg"][1], 4)],
           "radius_with_hP": sig(s["cell_radius_with_hP"][0], 9),
           "uniform": [p["codewords"], p["worst"] < 1e-12], "regular": sig(abs(p["regular"][0] - p["regular"][1]), 1)}
    if got["facets"][0] != got["facets"][1] or not got["formula_vs_clip"] or not all(got["uniform"][1:]) or got != w["cell_claim"]:
        out.append(f"Pass 03's cell: {got}")
    w["w2"] = got
    return out


def w3_phase(w):
    """Pass 04: the phase floor, the phase-integrated, radial and homothetic lower bounds, rebuilt; the inner core
    lambda (a minimum) and the sharp cell radius (a maximum) found to 10^-12 by zooming - a sampled minimum is too
    large and a sampled maximum too small, the unsafe side for both - against the recorded values; the sandwich
    L# <= h_U* <= h_P and lambda P inside U* on the spike body itself"""
    out, s = [], w["spike"]
    c4 = w["validations"]["04"]["constants_and_sanity"]["spike_cell"]
    got = {"floor": sig(s["phase_floor"], 15), "lower": [sig(s["phase_area_lower"], 15), sig(s["radial_area_lower"], 15), sig(s["homothetic_area_lower"], 12)],
           "lambda": [sig(s["lambda"], 12), sig(s["lambda_at"], 9), c4["homothetic_core_lambda"] <= s["lambda"]],
           "recorded_core_there": [sig(c4["homothetic_core_lambda"] * s["at_lambda"]["hP"] - s["at_lambda"]["Lsharp"], 2),
                                   sig(s["at_lambda"]["hU"] - c4["homothetic_core_lambda"] * s["at_lambda"]["hP"], 2)],
           "sharp_radius": [sig(s["sharp_cell_radius"], 12), sig(s["sharp_cell_radius_at"], 9), c4["sharp_cell_radius_numeric"] >= s["sharp_cell_radius"]],
           "bracket": s["radial_area_lower"] <= s["true_area"] <= s["outer_area"], "sandwich": s["sandwich"]}
    if not got["bracket"] or not all(got["sandwich"]) or got != w["phase_claim"]:
        out.append(f"Pass 04's phase envelope: {got}")
    w["w3"] = got
    return out


def w4_skeleton(w):
    """Pass 05: the uniform M = 128 area form's spectrum (numerically and in closed form); the signature on random
    fans; the dual's extreme witnesses on 12 directions and their sparsity on a shifted grid; the M = 8 basis"""
    out, k = [], w["skeleton"]
    got = {"signature_M128": k["signature_M128"], "zero_modes": k["zero_modes"], "extremes": [sig(x, 8) for x in k["eigen_extremes"]],
           "closed_form": k["closed_form"] < 1e-9, "random_fans": k["random_fans"], "dual": k["dual"],
           "toy": [k["toy"]["interval"][0], sig(k["toy"]["interval"][1], 15), max(abs(a - b) for a, b in zip(k["toy"]["quadratic"], k["toy"]["exact"][:3])) < 1e-9,
                   sig(k["toy"]["minimum"][1], 15)]}
    ok = got["signature_M128"] == [1, 2, 125] and all(v == [1, 2, int(m) - 3] for m, v in got["random_fans"].items()) and got["dual"] == [6, 40, 6] and got["toy"][2]
    if not ok or got != w["skeleton_claim"]:
        out.append(f"Pass 05's skeleton: {got}")
    w["w4"] = got
    return out


def w5_code(w):
    """what the passes ship, read after the rebuild and never run"""
    facts = {"lines": {k: v.count("\n") for k, v in sorted(w["code"].items())}}
    facts.update(code_probes(w["code"], w["validations"]))
    w["w5"] = facts
    return [] if facts == w["code_facts"] else [f"the scripts: {facts}"]


def code_probes(code, V):
    """read, never run: each script prints exactly its VALIDATION's replay block - Pass 02's constants by the
    formulas rebuilt here (the step by a ceiling), Pass 03's fan and bounds (quantized without a guard), Pass 04's
    extremes on a grid of 240,000 angles with no refinement, Pass 05's spectrum in closed form and the dual's
    extremes; the rest of each VALIDATION - Pass 03's cell radius and regular polygon, Pass 04's phase and
    homothetic bounds and its figure for Pass 03's radius, Pass 05's eigenvalue extremes, sparsity example and
    toy basis - is computed by no script shipped"""
    sq = {k.split("Pass_")[1][:2]: gate.squash(v) for k, v in code.items()}
    keys = lambda text: sorted(set(re.findall(r'"([A-Za-z0-9_]+)":', text)))
    printed = {"02": keys(sq["02"].split("return{")[1].split("}")[0]), "03": keys(sq["03"].split("out={")[1]),
               "04": keys(sq["04"].split("print(json.dumps({")[1]), "05": sorted(k for k in ("signature_M128", "dual_extremes_S12") if f'out["{k}"]' in sq["05"] or f'"{k}":' in sq["05"])}
    replay = {"02": sorted(k for k in V["02"]["constants"]["global_upper_cap_example"]), "03": sorted(V["03"]["replay_script_output"]),
              "04": sorted(V["04"]["replay_script_output"]), "05": sorted(V["05"]["replay_script_output"])}
    return {"prints_the_replay_block": {p: printed[p] == replay[p] for p in printed},
            "step_by_ceiling": "adjacent_index_step=math.ceil((V_alpha+q)/q)" in sq["02"], "unguarded_quantization": "b=[r+q*math.ceil((x-r)/q)forxinh]" in sq["03"],
            "grid": re.findall(r"forninrange\((\d+)\)", sq["04"]), "closed_form_spectrum": "2*(math.cos(k*alpha)-math.cos(alpha))/math.sin(alpha)" in sq["05"],
            "unshipped": sorted(k for k, text in (("pass03_cell_radius", "numerical_cell_envelope_epsilon"), ("pass04_phase_bound", "phase_area_lower"),
                                                  ("pass04_quote_of_pass03", "pass03_cell_radius"), ("pass05_toy", "toy_parametric"),
                                                  ("pass05_eigen_extremes", "min_eigenvalue")) if not any(text in s for s in sq.values()))}


def p1_package(w):
    """the four VALIDATION files: each document's record against the archive and the text; their sanity numbers
    against those recomputed here; the two passes' records of Pass 03's cell radius against each other"""
    out, V, s, k = [], w["validations"], w["spike"], w["skeleton"]
    leaves = {row[0]: row for row in w["manifest"]["leaves"]}
    for p in PASSES:
        rec, (_, size, digest), text = V[p]["canonical_source"], leaves[DOCS[p]], w["texts"][p]
        if (rec["sha256"], rec["bytes"], rec["file"], rec["lines"], rec["utf8"], rec["hidden_ascii_control_count"]) \
                != (digest, size, DOCS[p].split("/")[-1], text.count("\n") + 1, True, sum(1 for ch in text if ord(ch) < 32 and ch not in "\t\n\r")) \
                or V[p]["status"] != "PASS":
            out.append(f"Pass {p}: VALIDATION's record of the document")
    c3 = V["03"]["constants_and_sanity"]["spike_cell"]
    mine3 = {"active_facets_after_redundancy": s["active_facets"], "outer_polygon_area_Aplus": s["outer_area"], "outer_polygon_perimeter": s["outer_perimeter"],
             "cell_perimeter_lower": s["cell_perimeter_lower"], "cell_area_lower_Aminus": s["cell_area_lower"], "true_area": s["true_area"]}
    c4 = V["04"]["constants_and_sanity"]["spike_cell"]
    # the sampled extremes (the core's lambda, its area, the sharp radius) are W3's
    mine4 = {"active_facets": s["active_facets"], "outer_area": s["outer_area"], "phase_perimeter_lower": s["phase_perimeter_lower"],
             "phase_area_lower": s["phase_area_lower"], "radial_area_lower": s["radial_area_lower"]}
    bad = [key for key, x in mine3.items() if not close(x, c3[key], 1e-12)] + [key for key, x in mine4.items() if not close(x, c4[key], 1e-12)]
    s5 = V["05"]["structural_sanity"]
    if s5["uniform_area_signature_M128"]["zero_mode_indices"] != k["zero_modes"] or [s5["uniform_area_signature_M128"][x] for x in ("positive", "zero", "negative")] \
            != k["signature_M128"] or [s5["translation_dual_grid_S12"][x] for x in ("two_active_extremes", "three_active_extremes")] != k["dual"][:2]:
        bad.append("Pass 05's structural sanity")
    if bad:
        out.append(f"VALIDATION's numbers against this tree's: {bad}")
    w["p1"] = {"pass03_radius": [c3["numerical_cell_envelope_epsilon"], c4["pass03_cell_radius_numeric"], s["cell_radius"]]}
    return out


CHECKS = {"A0": a0_anchors, "W1": w1_budget, "W2": w2_cell, "W3": w3_phase, "W4": w4_skeleton, "W5": w5_code, "P1": p1_package}
DEPENDS = {"A0": {"texts"}, "W1": {"budget", "validations", "trials", "identities", "budget_claim"}, "W2": {"spike", "polygons", "cell_claim"},
           "W3": {"spike", "validations", "phase_claim"}, "W4": {"skeleton", "skeleton_claim"}, "W5": {"code", "validations", "code_facts"},
           "P1": {"validations", "manifest", "texts", "spike", "skeleton"}}


def drill_cases(base):
    def edit(obj, fn):
        x = copy.deepcopy(obj)
        fn(x)
        return x

    T, V = base["texts"], base["validations"]
    return [
        ("K0-unmodified", "control", {}, set()),
        ("K1-texts-crlf", "control", {"texts": {p: t.replace("\n", "\r\n") for p, t in T.items()}}, set()),
        ("M1-pass02-text", "mutation", {"texts": {**T, "02": T["02"].replace("0.013327012451412", "0.013327012451413")}}, {"A0"}),
        ("M2-budget-constant", "mutation", {"budget": edit(base["budget"], lambda x: x["threshold"].update(beta_deep=0.04176))}, {"W1"}),
        ("M3-eps-exceeded", "mutation", {"trials": {**base["trials"], "worst_ratio": 1.01}}, {"W1"}),
        ("M4-facet-count", "mutation", {"spike": edit(base["spike"], lambda x: x.update(active_facets=104))}, {"W2", "P1"}),
        ("M5-uniform-formula", "mutation", {"polygons": {**base["polygons"], "worst": 1e-6}}, {"W2"}),
        ("M6-sandwich", "mutation", {"spike": edit(base["spike"], lambda x: x.update(sandwich=[True, True, False]))}, {"W3"}),
        ("M7-signature", "mutation", {"skeleton": edit(base["skeleton"], lambda x: x.update(signature_M128=[1, 3, 124]))}, {"W4", "P1"}),
        ("M8-toy", "mutation", {"skeleton": edit(base["skeleton"], lambda x: x["toy"].update(quadratic=[-0.5, 4.4, -8.8]))}, {"W4"}),
        ("M9-code-claim", "mutation", {"code_facts": {}}, {"W5"}),
        ("M10-validation-digest", "mutation", {"validations": edit(V, lambda x: x["03"]["canonical_source"].update(sha256="0" * 64))}, {"P1"}),
        ("M11-validation-number", "mutation", {"validations": edit(V, lambda x: x["04"]["constants_and_sanity"]["spike_cell"].update(radial_area_lower=0.8440076))},
         {"P1"}),
    ]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    args = ap.parse_args()
    base = world(load_inputs())

    def build():
        return {**base, **copy.deepcopy(CLAIMS)}

    if args.blind:
        CHECKS[args.blind] = lambda w: []
        args.drill = True
    w = build()
    results = {c: fn(w) for c, fn in CHECKS.items()}
    for c, f in results.items():
        print(f"{c} {'PASS' if not f else 'FAIL'}", *(f"\n     {x}" for x in f[:6]))
    for key in ("w1", "w2", "w3", "w4", "w5", "p1"):
        print(key, "=", json.dumps(w.get(key), default=float, ensure_ascii=False))
    if not args.drill:
        return
    cases = drill_cases(base)
    if args.blind:
        cases = [c for c in cases if args.blind in c[3]]
    d = gate.run_drill(build, CHECKS, DEPENDS, cases)
    summary = gate.summarize(d, CHECKS)
    print(gate.report_drill(summary))
    for x in d:
        if not x["ok"]:
            print("   DRILL FAIL", x)
    if args.blind:
        n = sum(1 for x in d if args.blind in x["expected"] and args.blind not in x["tripped"])
        print(f"blind {args.blind}: drill reported it blind in {n} cases (nothing written)")
        return
    log = {"run": "RUN-042", "subject": "DLMVC's four deep passes on Round 04", "documents": DOCS,
           "checks": {c: {"pass": not f, "failures": f} for c, f in results.items()},
           **{k: w.get(k) for k in ("w1", "w2", "w3", "w4", "w5", "p1")}, "drill": summary}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
