"""RUN-061 - the LESR / UESFCM Lebesgue midpoint handoff: certificate line and counter-certificate line.

The midpoint handoff (LESR-LUC-MID-HANDOFF-v0.1, 2026-09-20) is a work contract, not a theorem. It splits the line into a
cloud certificate / analytic-closure line and a local counter-certificate / heavy-compute line, keeps three target
ledgers apart (the global value, the root-6217 barrier shape, the global extremal shape), and states that proof
closure does not imply shape irrelevance (cell 131: closed for A > A3+ = 0.834781191, yet a numerical candidate at
0.8349862484449208 < 0.8349865). It records the canonical zero-rotation barrier to 34-37 digits and what Paper 07
completed (13 intervals, 8 bridges, 6 triple lines, b*, B5's balances, B3's subgradient g3 and multiplier -g3), sets
Paper 08's attack order (evenness => m'(0) = 0; a topology transition at rho ~ 0.01409689011226), and gives the local
line its priorities: a positive-rotation lower-area branch, new contact topology, dual infeasibility, new witnesses,
and heavy-compute tasks, with grades for counter-certificates and certificates and an artifact index. Here every
number is set against this tree's own computations, and each local-line priority against what RUN-048 ... RUN-060
found.

Checks
  A0 anchors      the statements below occur in the document as written
  W1 barrier      sec. 5: x3*, theta*, x5*, alpha* and the area against the 70-digit construction (RUN-057)
  W2 paper07      sec. 6: b*, g3, 0 < b* < Ltheta; the bridges, triple lines and balances; B3's subgradient (RUN-057)
  W3 ledgers      sec. 3-4: the public bracket (RUN-002); A3+ (RUN-056); cell 131 closed for A3+ yet below 0.8349865 (RUN-049)
  W4 counter      sec. 10-12: what this tree found for CC-08A (a lower branch), CC-08B (new topology), CC-08C (duality)
  W5 attack       sec. 9: evenness, and m'(0) = 0 not from it; the Cycle 14 transition is one sample of two changes
  W6 artifacts    sec. 25: the artifact index against the archive
  P1 package      the VALIDATION record against the bytes and the archive; the next node against Paper 08's title

Usage: python code/run061_lesr_midpoint_handoff.py [--drill] [--blind CID]
"""
import argparse
import copy
import hashlib
import inspect
import json
import re

import mpmath as mp

import gate
import run046_uesfcm_cycles_07_09 as r46
import run048_uesfcm_cycles_12_14 as r48
import run057_lesr_paper07 as r57
from corpus import SOURCES, TREE, source_bytes, walk_sources

FOLDER = "main.zip!/LESR_Skew_Field_Variational/"
DOC = FOLDER + "LESR_Lebesgue_Midpoint_Handoff_Certificate_vs_CounterCertificate_v0.1.md"
VALIDATION = FOLDER + "LESR_Lebesgue_Midpoint_Handoff_VALIDATION.json"
PAPER08 = FOLDER + "LESR_Paper08_Package_v0.1.zip!/LESR_Paper08_Positive_Rotation_Certificate_Reduction_v0.1.md"
LOG = TREE / "data" / "gate-logs" / "run061-lesr-midpoint-handoff.json"
LOGS = {n: TREE / "data" / "gate-logs" / f"{n}.json" for n in ("run002-round00-baseline-interface", "run048-uesfcm-cycles-12-14", "run049-uesfcm-cycles-15-17",
                                                                  "run055-lesr-paper05", "run056-lesr-paper06", "run057-lesr-paper07", "run059-lesr-paper09a",
                                                                  "run060-lesr-paper09b")}
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"
CACHE = TREE / "data" / "cache" / "run061-searches.json"     # data/cache is not committed
INDEX = ["LESR_Paper06_Actual_Lebesgue_Shape_State_and_First_Closure_Graph_v0.1.md", "LESR_Paper06_Actual_Closure_Graph_v0.1.json",
         "LESR_Paper06_Target_Specific_Ledgers_v0.1.json", "LESR_Paper07_Root6217_Barrier_Shape_Reconstruction_v0.1.md",
         "LESR_Paper07_Barrier_Shape_Certificate_v0.1.json", "LESR_Paper07_Verify_Barrier_Shape.py", "LESR_Paper07_COMPUTE_DEFERRED_Tasks_v0.1.json",
         "UESFCM_Lebesgue_Cycle_12_6217_Symmetric_Contact_Data.json", "UESFCM_Lebesgue_Cycle_12_6217_Rotation_Profile.json",
         "UESFCM_Lebesgue_Cycle_14_Rotation_Profile_Structure.json", "UESFCM_Lebesgue_Cycle_16_Tight_Aref_Certificate.json", "UESFCM_Lebesgue_Cycle_17_Package_v0.1.zip"]
PRINTED = {"theta": "0.4540452162931832966751150439895469", "x5": "0.0197709463479475491438550793632155",
           "alpha": "0.8481803697755840850400223402764489", "area": "0.8349861105592240998506623565577005921",
           "bstar": "0.0655836825508581909985249388028961", "g3": "-0.12279106273508322894766663227"}


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: l.id in (DOC, VALIDATION, PAPER08)) if d is not None}
    rows = json.loads(MANIFEST.read_text(encoding="utf-8"))["leaves"]
    return {"text": got[DOC].decode("utf-8"), "validation": json.loads(got[VALIDATION]), "bytes": {DOC: got[DOC], VALIDATION: got[VALIDATION]},
            "manifest_rows": {r[0]: r for r in rows if r[0] in (DOC, VALIDATION)},
            "names": sorted({seg for r in rows for seg in re.split(r"!?/", r[0])}),       # every file and nested-zip name on a leaf's path
            "paper08_title": got[PAPER08].decode("utf-8").split("\n")[1], "profile": r48.load_inputs()["profile"],
            "logs": {n: json.loads(p.read_text(encoding="utf-8")) for n, p in LOGS.items()}}


# ---------------------------------------------------------------- computations

def barrier():
    """RUN-057's construction at 70 digits: theta*, x5*, alpha*, Ltheta, b*, g3 and the area over the 13 intervals"""
    h = r57.hp_constants(70)
    return {k: h[k] for k in ("theta", "x5", "alpha", "Ltheta", "bstar", "g3", "area")}


def mirror(profile):
    """sec. 9 P08-A: the area at Cycle 12's positive samples and at their mirror images (x3, -y3, -rho, x5, -y5), on the
    verified hull"""
    out = []
    for s in profile["samples"][1:6]:
        v = [s["x3"], s["y3"], s["rho"], s["x5"], s["y5"]]
        out.append([s["rho"], r46.area(v), r46.area([v[0], -v[1], -v[2], v[3], -v[4]])])
    return out


def _key(name, fn, extra=""):
    import run008_round05_saturation_gate as r8
    import run009_round06_witness_exchange as r9
    digest = hashlib.sha256(inspect.getsource(fn).encode())
    for path in (r8.__file__, r9.__file__, r46.__file__, r57.__file__):
        digest.update(open(path, "rb").read())
    digest.update(extra.encode())
    return digest.hexdigest()


def searches(inputs):
    cached = json.loads(CACHE.read_text(encoding="utf-8")) if CACHE.exists() else {}
    out = {}
    jobs = (("barrier", barrier, lambda: barrier(), ""), ("mirror", mirror, lambda: mirror(inputs["profile"]), json.dumps(inputs["profile"]["samples"][1:6])))
    for name, fn, call, extra in jobs:
        key = _key(name, fn, extra)
        if cached.get(name, {}).get("key") != key:
            cached[name] = {"key": key, "value": json.loads(json.dumps(call()))}
            CACHE.parent.mkdir(parents=True, exist_ok=True)
            CACHE.write_text(json.dumps(cached, indent=1) + "\n", encoding="utf-8")
        out[name] = cached[name]["value"]
    return out


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

ANCHORS = {"A0": [r"0.8344\lea_{\mathrm{Leb}}\le0.8440935944.", r"\text{PROOF-CLOSED}\not\Rightarrow\text{SHAPE-IRRELEVANT}.", r"A>A_3^+=0.834781191,",
                  r"A\approx0.8349862484449208<0.8349865.", r"x_3^\star=x_3^0-s=-0.02097883209899.", r"\theta_\star=" + PRINTED["theta"] + r"\ldots",
                  r"x_5^\star=" + PRINTED["x5"] + r"\ldots", r"\alpha_\star=" + PRINTED["alpha"] + r"\ldots",
                  r"A_{\mathrm{barrier}}=" + PRINTED["area"] + r"\ldots", r"b_\star=" + PRINTED["bstar"] + r"\ldots", r"0<b_\star<L_\theta.",
                  r"g_3=" + PRINTED["g3"] + r"\ldots<0.", r"$$m'(0)=0.$$", r"\rho\approx0.01409689011226.",
                  r"m_{6217}(\rho)\gem_{6217}(0)\qquad\forall\rho\in[0,\pi/120].", r"\exists\rho>0:m_{6217}(\rho)<m_{6217}(0)?", "`COUNTER_CERTIFIED`"]}
CLAIMS = {
    "barrier_claim": {"theta": True, "x5": True, "alpha": True, "area": True, "x3": True},
    # sec. 6 I's subgradient (g3, 0) fails (margin -0.0663 over 72 directions); the valid first component lies in
    # [-0.0477, -0.0474]; the barrier is still the constrained minimum (least feasible rate 0.0354) - RUN-057
    "paper07_claim": {"bstar": True, "g3": True, "bstar_inside": True, "atoms": {"Lalpha": 2, "Ltheta": 4, "Lvert": 2, "zero": 4}, "triple": 6,
                      "balances": [True, True, True], "subgradient_margin": -0.0663, "feasible_least": 0.0354, "valid_g3": [-0.0477, -0.0474]},
    "ledgers_claim": {"bracket": ["0.8344", "0.8440935944"], "A3plus": 0.834781191,
                      "cell131": {"closed_for_A3plus": [True, True], "below_tight": [131], "at_or_below_0835": [131, 129, 125, 152, 150]}},
    "counter_claim": {"cc08a": {"profile_ratios": [0.1738, 0.2254], "branch_ratios": [0.225236, 0.225413, 0.225501, 0.225544], "lower_branch_found": False},
                      "cc08b": {"signature": [13, 18, 15], "slivers_along_critical": ["B5a3", "D", "B5a2"]},
                      "cc08c": {"dual_at_generic": True, "gradient": 0.39, "p07_split_subgradient": False}},
    "attack_claim": {"even": True, "cycle14_classes": [1, 8, 17, 1], "sample14": ["0.01409689011226", True],
                     "between_8_9": [0.008055365778435367, 0.009062286500739787]},
    "artifacts_claim": {"present": INDEX, "missing": []},
    "package_claim": {"digest": True, "manifest": True, "utf8": True, "delimiters": ["PASS", []],
                      "lines": ["CERTIFICATE_ANALYTIC_CLOSURE", "COUNTER_CERTIFICATE_HEAVY_COMPUTE"],
                      "next": ["Paper 08 — Positive-Rotation Barrier Closure", False]},
}


def agrees(mine, printed):
    """the printed digits are this value's, truncated or rounded: within one unit of the last printed digit"""
    mp.mp.dps = 80
    places = len(printed.split(".")[1])
    return bool(abs(mp.mpf(mine) - mp.mpf(printed)) < mp.mpf(10) ** -places)


def w1_barrier(w):
    b = w["search"]["barrier"]
    mp.mp.dps = 80
    got = {k: agrees(b[k], PRINTED[k]) for k in ("theta", "x5", "alpha", "area")}
    got["x3"] = bool(mp.mpf("-0.01215883209899") - mp.mpf("0.00882") == mp.mpf("-0.02097883209899"))
    w["w1"] = got
    return [] if got == w["barrier_claim"] else [f"the barrier: {got}"]


def w2_paper07(w):
    """sec. 6: b* and g3 to their printed digits, 0 < b* < Ltheta; RUN-057's bridges, triple lines and balances; and
    sec. 6 I: (g3, 0) is not a subgradient - the barrier is the constrained minimum with a smaller multiplier"""
    b, l57 = w["search"]["barrier"], w["logs"]["run057-lesr-paper07"]
    mp.mp.dps = 80
    got = {"bstar": agrees(b["bstar"], PRINTED["bstar"]), "g3": agrees(b["g3"], PRINTED["g3"]),
           "bstar_inside": bool(0 < mp.mpf(b["bstar"]) < mp.mpf(b["Ltheta"])), "atoms": l57["w2"]["atoms"], "triple": len(l57["w2"]["triple"]),
           "balances": l57["w3"]["balance"], "subgradient_margin": l57["w3"]["margin_72"], "feasible_least": l57["w3"]["feasible_least"],
           "valid_g3": l57["w3"]["valid"]}
    w["w2"] = got
    return [] if got == w["paper07_claim"] else [f"Paper 07's list: {got}"]


def w3_ledgers(w):
    l02, l49, l56 = w["logs"]["run002-round00-baseline-interface"], w["logs"]["run049-uesfcm-cycles-15-17"], w["logs"]["run056-lesr-paper06"]
    ms = l49["w6"]["minsearch"]
    got = {"bracket": [l02["claims"]["lower"], l02["claims"]["upper"]], "A3plus": l56["w4"]["ceiling"],
           "cell131": {"closed_for_A3plus": l49["w5"]["h131"]["structure"][-2:], "below_tight": ms[6], "at_or_below_0835": ms[3]}}
    w["w3"] = got
    return [] if got == w["ledgers_claim"] else [f"the ledgers: {got}"]


def w4_counter(w):
    """sec. 10-12. CC-08A: no positive rotation below m(0) - RUN-048's re-minimized profile, RUN-059's branch. CC-08B: new
    topology at rho > 0 - RUN-059's 13 -> 18 and 15, RUN-060's slivers. CC-08C: the finite dual is feasible even at a
    non-stationary placement (RUN-055), and Paper 07's split is not a subgradient (RUN-057)"""
    L = w["logs"]
    l48, l59, l60, l55 = L["run048-uesfcm-cycles-12-14"], L["run059-lesr-paper09a"], L["run060-lesr-paper09b"], L["run055-lesr-paper05"]
    got = {"cc08a": {"profile_ratios": l48["w7"]["circle"][4], "branch_ratios": l59["w5"]["ratios"], "lower_branch_found": min(l48["w7"]["circle"][4]) <= 0},
           "cc08b": {"signature": [l59["w2"]["barrier"][0], l59["w2"]["anchor"], l59["w3"]["pieces_at_minimum"][0]],
                     "slivers_along_critical": [p for p, _, _ in l60["w4"]["slivers"]["1e-05"]]},
           "cc08c": {"dual_at_generic": all(all(v) for v in l55["w3"]["certificates"].values()), "gradient": l55["w3"]["gradient"],
                     "p07_split_subgradient": L["run057-lesr-paper07"]["w3"]["margin_72"] >= 0}}
    w["w4"] = got
    return [] if got == w["counter_claim"] else [f"the counter-certificate line: {got}"]


def w5_attack(w):
    """sec. 9: m is even (the mirror image of every placement has the same area), which gives m'(0+) = -m'(0-), not m'(0) = 0:
    a kink stays even. Cycle 14's sequence changes twice over the sampled profile - generic A to generic B between samples 8
    and 9, and one degenerate sample (14) inside B - and 0.01409689011226 is that sample's rho"""
    s, l48 = w["search"]["mirror"], w["logs"]["run048-uesfcm-cycles-12-14"]
    prof = w["profile"]["samples"]
    got = {"even": max(abs(a - b) for _, a, b in s) < 1e-15, "cycle14_classes": l48["w7"]["skeletons"][4],
           "sample14": [repr(prof[14]["rho"])[:16], abs(prof[14]["rho"] - 0.01409689011226) < 1e-14], "between_8_9": [prof[8]["rho"], prof[9]["rho"]]}
    w["w5"] = got
    return [] if got == w["attack_claim"] else [f"Paper 08's attack order: {got}"]


def w6_artifacts(w):
    names = set(w["names"])
    got = {"present": [n for n in INDEX if n in names], "missing": [n for n in INDEX if n not in names]}
    w["w6"] = got
    return [] if got == w["artifacts_claim"] else [f"the artifact index: {got}"]


def p1_package(w):
    v, B = w["validation"], w["bytes"]
    sha = lambda b: hashlib.sha256(b).hexdigest()
    body = B[DOC].decode("utf-8")
    got = {"digest": v["sha256"] == sha(B[DOC]), "manifest": all(w["manifest_rows"][k][2] == sha(b) for k, b in B.items()), "utf8": v["utf8"] is True,
           "delimiters": [v["math_delimiters"], sorted(set(re.findall(r"\\\(|\\\)|\\\[|\\\]", body)))], "lines": [v["cloud_mainline"], v["local_mainline"]],
           "next": [v["next_cloud_node"], "Positive-RotationBarrierClosure" in gate.squash(w["paper08_title"])]}
    w["p1"] = got
    return [] if got == w["package_claim"] else [f"the package: {got}"]


def a0_anchors(w):
    text = gate.squash(w["text"])
    return [f"anchor not found: {a[:60]}" for a in ANCHORS["A0"] if a not in text]


CHECKS = {"A0": a0_anchors, "W1": w1_barrier, "W2": w2_paper07, "W3": w3_ledgers, "W4": w4_counter, "W5": w5_attack, "W6": w6_artifacts, "P1": p1_package}
DEPENDS = {"A0": {"text"}, "W1": {"search", "barrier_claim"}, "W2": {"search", "logs", "paper07_claim"}, "W3": {"logs", "ledgers_claim"},
           "W4": {"logs", "counter_claim"}, "W5": {"search", "logs", "profile", "attack_claim"}, "W6": {"names", "artifacts_claim"},
           "P1": {"validation", "bytes", "manifest_rows", "paper08_title", "package_claim"}}


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

    text, s, L = base["text"], base["search"], base["logs"]
    return [
        ("K0-unmodified", "control", {}, set()),
        ("K1-crlf", "control", {"text": text.replace("\n", "\r\n")}, set()),
        ("K2-validation-keys-sorted", "control", {"validation": json.loads(json.dumps(base["validation"], sort_keys=True))}, set()),
        ("M1-cell131-candidate", "mutation", {"text": text.replace("0.8349862484449208", "0.8349862484449209")}, {"A0"}),
        ("M2-theta", "mutation", {"search": edit(s, lambda x: x["barrier"].update(theta="0.4540452162931832966751150439895569"))}, {"W1"}),
        ("M3-bstar", "mutation", {"search": edit(s, lambda x: x["barrier"].update(bstar="0.06558368255085819099852493880290"))}, {"W2"}),
        ("M4-p07-subgradient", "mutation", {"logs": edit(L, lambda x: x["run057-lesr-paper07"]["w3"].update(margin_72=0.01))}, {"W2", "W4"}),
        ("M5-cell131-ranking", "mutation", {"logs": edit(L, lambda x: x["run049-uesfcm-cycles-15-17"]["w6"]["minsearch"].__setitem__(6, [131, 129]))}, {"W3"}),
        ("M6-A3plus", "mutation", {"logs": edit(L, lambda x: x["run056-lesr-paper06"]["w4"].update(ceiling=0.8347812))}, {"W3"}),
        ("M7-lower-branch", "mutation", {"logs": edit(L, lambda x: x["run048-uesfcm-cycles-12-14"]["w7"]["circle"].__setitem__(4, [-0.01, 0.2254]))}, {"W4"}),
        ("M8-corner-sliver", "mutation",
         {"logs": edit(L, lambda x: x["run060-lesr-paper09b"]["w4"]["slivers"].update({"1e-05": [["B5v2", 2.6876, 0.5]]}))}, {"W4"}),
        ("M9-mirror", "mutation", {"search": edit(s, lambda x: x["mirror"][2].__setitem__(2, x["mirror"][2][2] + 1e-12))}, {"W5"}),
        ("M10-cycle14-classes", "mutation", {"logs": edit(L, lambda x: x["run048-uesfcm-cycles-12-14"]["w7"]["skeletons"].__setitem__(4, [1, 9, 16, 1]))},
         {"W5"}),
        ("M11-artifact-missing", "mutation", {"names": [n for n in base["names"] if n != "UESFCM_Lebesgue_Cycle_16_Tight_Aref_Certificate.json"]}, {"W6"}),
        ("M12-validation-digest", "mutation", {"validation": {**base["validation"], "sha256": "0" * 64}}, {"P1"}),
        ("M13-paper08-title", "mutation", {"paper08_title": "## Paper 08 — Positive-Rotation Barrier Closure"}, {"P1"}),
    ]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    args = ap.parse_args()
    inputs = load_inputs()
    base = {**inputs, "search": searches(inputs)}

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

    if args.blind:
        CHECKS[args.blind] = lambda w: []
        args.drill = True
    w = build()
    results = {}
    for c, fn in CHECKS.items():
        try:
            results[c] = fn(w)
        except KeyError as e:
            results[c] = [f"claim missing: {e}"]
    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", "w6", "p1"):
        print(key, "=", json.dumps(w.get(key), default=str, 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-061", "subject": "the LESR / UESFCM Lebesgue midpoint handoff: certificate line and counter-certificate line", "document": DOC,
           "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", "w6", "p1")}, "drill": summary}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
