"""Crown Landmark (PI-BLD-0001-V01) assembled-model QA script.

Run (Blender 5.2, background; the model is opened read-only, nothing is saved back):
  blender.exe --background --factory-startup <assembled.blend> --python qa_check.py -- --out <dir>
              [--baseline <qa_baseline.json>] [--skip-export] [--delete-glb] [--strict]

Writes to --out:  qa_report.json  QA_SUMMARY.md  qa_baseline.json  <blend>_qa.glb (export round-trip, unless --skip-export)
Units metres, Z up, front = -Y. Targets come from cl_common.py when it is next to this script (else an embedded copy).

Checks (each item is pass / warn / fail / info; one failing check never stops the others):
  1 Contract      collections, name prefixes, CL_* materials, identity transforms, no modifiers, no empty meshes, budgets
  2 Targets       R06 bounds, deck slabs, tower glass, roof, rib tips, entry arch and portal (ray measured)
  3 Mesh health   loose geometry, degenerate faces, non-manifold edges, flipped/inverted faces, duplicates, outliers;
                  open (zero-thickness) shells are classified separately and only warned
  4 Interference  BVH triangle overlaps between collections (Ribs/Tower and Ribs/Crown must be 0)
  5 Entry opening +Y rays from y=-100 at z=1.0/1.7/3.0/4.4, x=-4..4; arch and portal clear sizes by sweeps
  6 Export        glTF binary round-trip into an empty scene (runs last; it replaces the loaded scene)
  7 Regression    writes qa_baseline.json; with --baseline reports changes beyond tolerance
Exit code is 0 unless --strict is given (then 1 when any item fails).
"""
import sys
import os
import re
import json
import math
import time
import struct
import hashlib
import datetime
import traceback

sys.dont_write_bytecode = True
import numpy as np
import bpy
from mathutils import Vector
from mathutils.bvhtree import BVHTree

VERSION = "1.0"
try:
    SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
except NameError:  # pragma: no cover
    SCRIPT_DIR = os.getcwd()

# ------------------------------------------------------------------ targets (embedded copy of cl_common / R06) --
T = dict(
    HEIGHT=240.0,
    FOUNDATION=(160.0, 120.0),
    FOUNDATION_BOTTOM=-1.2,
    DECKS=[(18.0, 145.0, 106.0), (36.0, 125.0, 90.0), (54.0, 105.0, 76.0)],
    TOWER_BASE=(68.0, 54.0),
    TOWER_ROOF_Z=216.0,
    ENTRY_ARCH=(18.0, 14.0),
    ENTRY_PORTAL=(8.0, 4.5),
    RIBS={"R1": ((-58, -40), (-14, -13), 240.0), "R2": ((58, -40), (14, -13), 238.0),
          "R3": ((-64, 6), (-27, 5), 234.0), "R4": ((64, 6), (27, 5), 232.0),
          "R5": ((-40, 44), (-13, 19), 236.0), "R6": ((40, 44), (13, 19), 238.0)},
    PALETTE=["ivory", "glass", "gold", "amber", "water", "stone", "parapet"],
)
TARGETS_SOURCE = "embedded copy"
TARGETS_NOTE = ""


def load_targets():
    """Prefer the live cl_common constants (the single source of truth); note any difference from the embedded copy."""
    global TARGETS_SOURCE, TARGETS_NOTE
    try:
        if SCRIPT_DIR not in sys.path:
            sys.path.insert(0, SCRIPT_DIR)
        import cl_common as C
        live = dict(HEIGHT=float(C.HEIGHT), FOUNDATION=tuple(C.FOUNDATION), DECKS=[tuple(d) for d in C.DECKS],
                    TOWER_BASE=tuple(C.TOWER_BASE), TOWER_ROOF_Z=float(C.TOWER_ROOF_Z),
                    ENTRY_ARCH=tuple(C.ENTRY_ARCH), ENTRY_PORTAL=tuple(C.ENTRY_PORTAL),
                    RIBS={k: (tuple(v[0]), tuple(v[1]), float(v[2])) for k, v in C.RIBS.items()},
                    PALETTE=[k[len("CL_"):] if k.startswith("CL_") else k for k in C._PALETTE.keys()])
        diffs = [k for k, v in live.items() if json.dumps(v, sort_keys=True, default=list) != json.dumps(T[k], sort_keys=True, default=list)]
        T.update(live)
        TARGETS_SOURCE = "cl_common.py (" + os.path.join(SCRIPT_DIR, "cl_common.py") + ")"
        if diffs:
            TARGETS_NOTE = "live cl_common differs from the embedded copy for: " + ", ".join(diffs)
    except Exception as e:  # keep going with the embedded copy
        TARGETS_NOTE = "cl_common import failed (" + repr(e) + "); using embedded targets"


# ------------------------------------------------------------------ tolerances / policy ------------------------
TOL = dict(bounds=0.05, deck_z=0.05, deck_xy=0.05, tower_glass=1.5, roof_z=0.05, rib_tip=0.1, entry=0.1,
           ident=1e-6, area_eps=1e-8, edge_eps=1e-6, dup_grid=1e-4, glb_bounds=0.01, baseline_m=0.05)
EXPECTED_COLLECTIONS = ["Podium", "Tower", "Ribs", "Entrance", "Crown"]
PREFIX = {"Podium": [r"^Podium_.+"], "Tower": [r"^Tower_.+"], "Ribs": [r"^Rib_R[1-6]$", r"^Fin_.+"],
          "Entrance": [r"^Entry_.+"], "Crown": [r"^Crown_.+"]}
PREFIX_TEXT = {"Podium": "Podium_*", "Tower": "Tower_*", "Ribs": "Rib_R1..R6 or Fin_*", "Entrance": "Entry_*", "Crown": "Crown_*"}
MODULE_TRI_BUDGET, TOTAL_TRI_BUDGET = 150_000, 1_000_000
GLB_LIMIT_BYTES = 25 * 1024 * 1024
INTERFERENCE_PAIRS = [  # (collA, collB, required_zero)
    ("Ribs", "Tower", True), ("Ribs", "Crown", True), ("Ribs", "Entrance", False), ("Ribs", "Podium", False),
    ("Entrance", "Podium", False), ("Crown", "Tower", False),
    ("Podium", "Tower", False), ("Podium", "Crown", False), ("Entrance", "Tower", False), ("Entrance", "Crown", False),
]
RAY_Z = (1.0, 1.7, 3.0, 4.4)
RAY_X = (-4.0, -2.0, 0.0, 2.0, 4.0)
LOBBY_BACK_PREFIX = "Entry_lobby_back_"
ORDER = {"info": 0, "pass": 0, "warn": 1, "fail": 2}


# ------------------------------------------------------------------ small helpers ------------------------------
def argv_after_dashes():
    return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []


def parse_args():
    a = argv_after_dashes()

    def val(name, default=None):
        return a[a.index(name) + 1] if name in a and a.index(name) + 1 < len(a) else default
    return dict(out=os.path.abspath(val("--out", os.path.join(os.getcwd(), "qa_out"))),
                baseline=val("--baseline"), skip_export="--skip-export" in a, delete_glb="--delete-glb" in a,
                strict="--strict" in a)


def f(v, nd=3):
    if v is None:
        return "-"
    if isinstance(v, (int, np.integer)):
        return str(int(v))
    if isinstance(v, (float, np.floating)):
        return ("%." + str(nd) + "f") % v
    return str(v)


def item(iid, title, status, detail="", measured=None, expected=None, tol=None, unit=None, objects=None, data=None,
         baseline=True):
    return dict(id=iid, title=title, status=status, detail=detail, measured=measured, expected=expected, tol=tol,
                unit=unit, objects=objects, data=data, baseline=baseline)


def cmp_item(iid, title, measured, expected, tol, unit="m", detail="", objects=None, fail_status="fail"):
    if measured is None or (isinstance(measured, float) and not math.isfinite(measured)):
        return item(iid, title, fail_status, "not measurable. " + detail, None, expected, tol, unit, objects)
    ok = abs(measured - expected) <= tol + 1e-9
    d = "%s (delta %+.3f %s, tol +/-%s)" % (detail, measured - expected, unit, f(tol)) if detail else \
        "delta %+.3f %s, tol +/-%s" % (measured - expected, unit, f(tol))
    return item(iid, title, "pass" if ok else fail_status, d.strip(), measured, expected, tol, unit, objects)


def worst(items):
    w = None
    for it in items:
        if it["status"] in ("pass", "warn", "fail"):
            if w is None or ORDER[it["status"]] > ORDER[w]:
                w = it["status"]
    return w or "info"


def collect_names(objs, limit=None):
    objs = list(objs)
    return objs if limit is None else objs[:limit]


# ------------------------------------------------------------------ scene context -----------------------------
class Geo:
    """World-space numpy arrays of one evaluated mesh object."""
    pass


class Ctx:
    def __init__(self, args):
        self.args = args
        self.blend_name = os.path.basename(bpy.data.filepath)
        self.dg = bpy.context.evaluated_depsgraph_get()
        self.mesh_obs = [ob for ob in bpy.data.objects if ob.type == "MESH"]
        self.coll = {}      # object name -> primary collection name
        self.geo = {}       # name -> Geo
        self.geo_errors = {}
        self.trees = {}
        self.results = []   # finished check dicts
        self.extra = {}     # data shared between checks (export info ...)
        for c in bpy.data.collections:
            for ob in c.objects:
                self.coll.setdefault(ob.name, c.name)
        for ob in bpy.context.scene.collection.objects:
            self.coll.setdefault(ob.name, "<scene root>")
        for ob in bpy.data.objects:
            self.coll.setdefault(ob.name, "<none>")
        self._build_geo()
        self._build_trees()

    def _build_geo(self):
        for ob in self.mesh_obs:
            try:
                self.geo[ob.name] = self._extract(ob)
            except Exception as e:
                self.geo_errors[ob.name] = repr(e)

    def _extract(self, ob):
        ev = ob.evaluated_get(self.dg)
        me = ev.to_mesh()
        try:
            g = Geo()
            nv, ne, nl, npoly = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons)
            co = np.empty(nv * 3, np.float32)
            me.vertices.foreach_get("co", co)
            co = co.reshape(nv, 3).astype(np.float64)
            M = np.array(ob.matrix_world, dtype=np.float64)
            R = M[:3, :3]
            g.co = co @ R.T + M[:3, 3]
            ed = np.empty(ne * 2, np.int32)
            if ne:
                me.edges.foreach_get("vertices", ed)
            g.edges = ed.reshape(ne, 2)
            g.lv = np.empty(nl, np.int32)
            g.le = np.empty(nl, np.int32)
            if nl:
                me.loops.foreach_get("vertex_index", g.lv)
                me.loops.foreach_get("edge_index", g.le)
            g.ps = np.empty(npoly, np.int32)
            g.pt = np.empty(npoly, np.int32)
            g.area = np.empty(npoly, np.float32)
            nrm = np.empty(npoly * 3, np.float32)
            cen = np.empty(npoly * 3, np.float32)
            g.mat = np.zeros(npoly, np.int32)
            if npoly:
                me.polygons.foreach_get("loop_start", g.ps)
                me.polygons.foreach_get("loop_total", g.pt)
                me.polygons.foreach_get("area", g.area)
                me.polygons.foreach_get("normal", nrm)
                me.polygons.foreach_get("center", cen)
                try:
                    me.polygons.foreach_get("material_index", g.mat)
                except Exception:
                    pass
            g.normal = nrm.reshape(npoly, 3).astype(np.float64) @ R.T
            g.center = cen.reshape(npoly, 3).astype(np.float64) @ R.T + M[:3, 3]
            me.calc_loop_triangles()
            nt = len(me.loop_triangles)
            tv = np.empty(nt * 3, np.int32)
            tp = np.empty(nt, np.int32)
            if nt:
                me.loop_triangles.foreach_get("vertices", tv)
                me.loop_triangles.foreach_get("polygon_index", tp)
            g.tv = tv.reshape(nt, 3)
            g.tp = tp
            g.nv, g.ne, g.nl, g.npoly, g.nt = nv, ne, nl, npoly, nt
            if nv:
                g.lo, g.hi = g.co.min(axis=0), g.co.max(axis=0)
            else:
                g.lo = g.hi = np.zeros(3)
            return g
        finally:
            ev.to_mesh_clear()

    def _build_trees(self):
        for name, g in self.geo.items():
            if g.nt == 0:
                continue
            try:
                self.trees[name] = BVHTree.FromPolygons([tuple(v) for v in g.co.tolist()], [tuple(t) for t in g.tv.tolist()],
                                                        all_triangles=True)
            except Exception as e:
                self.geo_errors[name] = "bvh: " + repr(e)
        self.tnames = list(self.trees.keys())
        if self.tnames:
            self.tlo = np.array([self.geo[n].lo for n in self.tnames]) - 1e-6
            self.thi = np.array([self.geo[n].hi for n in self.tnames]) + 1e-6

    # ---- ray casting along +Y (bbox pre-filtered) --------------------------------------------------------
    def first_hit(self, origin, direction=(0.0, 1.0, 0.0), maxd=600.0, only=None):
        """First hit over every mesh (or only `only`). Returns (dist, name, point) or None."""
        o = Vector(origin)
        d = Vector(direction)
        if only is not None:
            names = [only] if only in self.trees else []
        elif tuple(direction) == (0.0, 1.0, 0.0):
            m = ((self.tlo[:, 0] <= o.x) & (self.thi[:, 0] >= o.x) & (self.tlo[:, 2] <= o.z) & (self.thi[:, 2] >= o.z)
                 & (self.thi[:, 1] >= o.y))
            names = [self.tnames[i] for i in np.nonzero(m)[0]]
        else:
            names = self.tnames
        best = None
        for n in names:
            h = self.trees[n].ray_cast(o, d, maxd)
            if h[0] is not None and (best is None or h[3] < best[0]):
                best = (h[3], n, h[0])
        return best

    def bounds(self):
        if not self.geo:
            return None
        lo = np.min([g.lo for g in self.geo.values()], axis=0)
        hi = np.max([g.hi for g in self.geo.values()], axis=0)
        return lo, hi


def coll_objects(ctx, cname):
    return [n for n in ctx.geo if ctx.coll.get(n) == cname]


# ------------------------------------------------------------------ 1. contract --------------------------------
def check_contract(ctx):
    items = []
    scene_root_children = {c.name for c in bpy.context.scene.collection.children}
    all_colls = {c.name for c in bpy.data.collections}
    missing = [c for c in EXPECTED_COLLECTIONS if c not in scene_root_children]
    items.append(item("contract.collections", "5 collections present under the scene", "fail" if missing else "pass",
                      ("missing: %s" % ", ".join(missing)) if missing else "Podium, Tower, Ribs, Entrance, Crown all linked",
                      len(EXPECTED_COLLECTIONS) - len(missing), 5, unit="count", objects=missing or None))
    extra = sorted(all_colls - set(EXPECTED_COLLECTIONS))
    items.append(item("contract.extra_collections", "no extra collections", "warn" if extra else "pass",
                      ("extra collections: %s" % ", ".join(extra)) if extra else "none", len(extra), 0, unit="count",
                      objects=extra or None))
    # membership
    outside, multi, nonmesh = [], [], []
    for ob in bpy.data.objects:
        cols = [c.name for c in ob.users_collection]
        in_exp = [c for c in cols if c in EXPECTED_COLLECTIONS]
        if ob.type in ("CAMERA", "LIGHT"):
            continue
        if ob.type != "MESH":
            nonmesh.append("%s (%s in %s)" % (ob.name, ob.type, ",".join(cols) or "no collection"))
            continue
        if not in_exp:
            outside.append("%s (in %s)" % (ob.name, ",".join(cols) or "no collection"))
        if len(cols) > 1:
            multi.append("%s (in %s)" % (ob.name, ",".join(cols)))
    items.append(item("contract.outside_collections", "no mesh objects outside the 5 collections", "fail" if outside else "pass",
                      "%d mesh objects outside" % len(outside) if outside else "all meshes are inside Podium/Tower/Ribs/Entrance/Crown",
                      len(outside), 0, unit="count", objects=outside or None))
    items.append(item("contract.nonmesh", "no non-mesh objects other than cameras/lights", "warn" if nonmesh else "pass",
                      "%d other objects" % len(nonmesh) if nonmesh else "none", len(nonmesh), 0, unit="count", objects=nonmesh or None))
    items.append(item("contract.multi_collection", "each mesh in exactly one collection", "warn" if multi else "pass",
                      "%d objects in several collections" % len(multi) if multi else "ok", len(multi), 0, unit="count",
                      objects=multi or None))
    # prefixes
    bad_prefix = []
    for cname in EXPECTED_COLLECTIONS:
        pats = [re.compile(p) for p in PREFIX[cname]]
        for ob in bpy.data.collections[cname].objects if cname in bpy.data.collections else []:
            if ob.type in ("CAMERA", "LIGHT"):
                continue
            if not any(p.match(ob.name) for p in pats):
                bad_prefix.append("%s in %s (expected %s)" % (ob.name, cname, PREFIX_TEXT[cname]))
    items.append(item("contract.prefixes", "object name prefixes match their collection", "fail" if bad_prefix else "pass",
                      "%d objects with a wrong prefix" % len(bad_prefix) if bad_prefix else
                      "Podium_*, Tower_*, Rib_R1..R6/Fin_*, Entry_*, Crown_* all respected",
                      len(bad_prefix), 0, unit="count", objects=bad_prefix or None))
    ribs = [n for n in (bpy.data.collections["Ribs"].objects.keys() if "Ribs" in bpy.data.collections else [])]
    miss_r = [r for r in T["RIBS"] if "Rib_" + r not in ribs]
    items.append(item("contract.principal_ribs", "Rib_R1..Rib_R6 each present", "fail" if miss_r else "pass",
                      ("missing: " + ", ".join(miss_r)) if miss_r else "all six principal ribs present",
                      6 - len(miss_r), 6, unit="count", objects=miss_r or None))
    dup_suffix = [ob.name for ob in bpy.data.objects if re.search(r"\.\d{3}$", ob.name)]
    items.append(item("contract.dup_names", "no Blender '.001' duplicate-name suffixes", "warn" if dup_suffix else "pass",
                      "%d" % len(dup_suffix) if dup_suffix else "none", len(dup_suffix), 0, unit="count", objects=dup_suffix or None))
    # materials
    no_mat, non_cl, local_cl, bad_idx = [], [], [], []
    pal = {"CL_" + p for p in T["PALETTE"]}
    mats_used = {}
    for ob in ctx.mesh_obs:
        slots = [s.material for s in ob.material_slots]
        if not slots or any(m is None for m in slots):
            no_mat.append("%s (slots: %s)" % (ob.name, [m.name if m else None for m in slots]))
            continue
        for m in slots:
            mats_used.setdefault(m.name, []).append(ob.name)
            if not m.name.startswith("CL_"):
                non_cl.append("%s -> %s" % (ob.name, m.name))
            elif m.name not in pal:
                local_cl.append("%s -> %s" % (ob.name, m.name))
        g = ctx.geo.get(ob.name)
        if g is not None and g.npoly and int(g.mat.max()) >= len(slots):
            bad_idx.append("%s (index %d, %d slots)" % (ob.name, int(g.mat.max()), len(slots)))
    items.append(item("contract.mat_present", "every mesh has a material in every slot", "fail" if no_mat else "pass",
                      "%d meshes without material" % len(no_mat) if no_mat else "all %d meshes have materials" % len(ctx.mesh_obs),
                      len(no_mat), 0, unit="count", objects=no_mat or None))
    items.append(item("contract.mat_cl_prefix", "materials carry the CL_ prefix", "fail" if non_cl else "pass",
                      "%d non-CL_ assignments" % len(non_cl) if non_cl else "all assigned materials are CL_*", len(non_cl), 0,
                      unit="count", objects=non_cl or None))
    local_mats = sorted({x.split(" -> ")[1] for x in local_cl})
    items.append(item("contract.mat_palette", "CL_ materials come from the shared palette (%s)" % "/".join(T["PALETTE"]),
                      "warn" if local_cl else "pass",
                      ("module-local CL_ materials outside the shared palette: %s" % ", ".join(local_mats)) if local_cl else
                      "only shared-palette materials", len(local_cl), 0, unit="count", objects=local_cl or None))
    items.append(item("contract.mat_index", "face material indices inside the slot range", "fail" if bad_idx else "pass",
                      "%d meshes" % len(bad_idx) if bad_idx else "ok", len(bad_idx), 0, unit="count", objects=bad_idx or None,
                      data=dict(materials_used={k: len(v) for k, v in sorted(mats_used.items())})))
    # transforms / modifiers / parents
    t_bad, m_bad, p_bad = [], [], []
    e = TOL["ident"]
    for ob in ctx.mesh_obs:
        probs = []
        if max(abs(x) for x in ob.location) > e:
            probs.append("location=%s" % [round(x, 4) for x in ob.location])
        if ob.rotation_mode == "QUATERNION":
            q = ob.rotation_quaternion
            if abs(q.w - 1) > e or max(abs(q.x), abs(q.y), abs(q.z)) > e:
                probs.append("rotation_quaternion=%s" % [round(x, 4) for x in q])
        elif ob.rotation_mode == "AXIS_ANGLE":
            probs.append("rotation_mode AXIS_ANGLE") if abs(ob.rotation_axis_angle[0]) > e else None
        elif max(abs(x) for x in ob.rotation_euler) > e:
            probs.append("rotation=%s" % [round(math.degrees(x), 3) for x in ob.rotation_euler])
        if max(abs(x - 1) for x in ob.scale) > e:
            probs.append("scale=%s" % [round(x, 4) for x in ob.scale])
        if max(abs(x) for x in ob.delta_location) > e or max(abs(x) for x in ob.delta_rotation_euler) > e \
                or max(abs(x - 1) for x in ob.delta_scale) > e:
            probs.append("delta transform")
        if probs:
            t_bad.append("%s: %s" % (ob.name, ", ".join(probs)))
        if ob.modifiers:
            m_bad.append("%s: %s" % (ob.name, ", ".join(m.type for m in ob.modifiers)))
        if ob.parent is not None or ob.constraints:
            p_bad.append("%s: parent=%s constraints=%d" % (ob.name, ob.parent.name if ob.parent else None, len(ob.constraints)))
    items.append(item("contract.transforms", "no unapplied transforms (loc 0, rot 0, scale 1)", "fail" if t_bad else "pass",
                      "%d objects carry a transform" % len(t_bad) if t_bad else "all %d meshes have identity transforms" % len(ctx.mesh_obs),
                      len(t_bad), 0, unit="count", objects=t_bad or None))
    items.append(item("contract.modifiers", "no modifiers", "fail" if m_bad else "pass",
                      "%d objects with modifiers" % len(m_bad) if m_bad else "none", len(m_bad), 0, unit="count", objects=m_bad or None))
    items.append(item("contract.parents", "no parents or constraints", "warn" if p_bad else "pass",
                      "%d objects" % len(p_bad) if p_bad else "none", len(p_bad), 0, unit="count", objects=p_bad or None))
    # empties
    empty = [ob.name for ob in ctx.mesh_obs if len(ob.data.vertices) == 0 or len(ob.data.polygons) == 0]
    empty += ["%s (geometry read error %s)" % (n, e_) for n, e_ in ctx.geo_errors.items()]
    items.append(item("contract.empty_meshes", "no empty meshes (no vertices or no faces)", "fail" if empty else "pass",
                      "%d empty or unreadable" % len(empty) if empty else "none", len(empty), 0, unit="count", objects=empty or None))
    # budgets
    per_c = {}
    for n, g in ctx.geo.items():
        per_c[ctx.coll.get(n, "?")] = per_c.get(ctx.coll.get(n, "?"), 0) + g.nt
    over = {c: t for c, t in per_c.items() if t > MODULE_TRI_BUDGET}
    items.append(item("contract.tri_budget_module", "each collection under %d triangles (SPEC)" % MODULE_TRI_BUDGET,
                      "warn" if over else "pass", "; ".join("%s=%d" % kv for kv in sorted(per_c.items())),
                      max(per_c.values()) if per_c else 0, MODULE_TRI_BUDGET, unit="tris", data=per_c, baseline=False))
    tot = sum(per_c.values())
    items.append(item("contract.tri_budget_total", "whole build under %d triangles (SPEC)" % TOTAL_TRI_BUDGET,
                      "warn" if tot > TOTAL_TRI_BUDGET else "pass", "total %d triangles" % tot, tot, TOTAL_TRI_BUDGET, unit="tris"))
    items.append(item("contract.counts", "inventory", "info",
                      "%d mesh objects; per collection: %s" % (len(ctx.mesh_obs), ", ".join(
                          "%s=%d" % (c, sum(1 for n in ctx.geo if ctx.coll.get(n) == c)) for c in EXPECTED_COLLECTIONS)),
                      len(ctx.mesh_obs), unit="count"))
    return items


# ------------------------------------------------------------------ 2. targets --------------------------------
def tip_of(g):
    zmax = g.co[:, 2].max()
    m = g.co[:, 2] >= zmax - 1e-3
    return g.co[m].mean(axis=0), int(m.sum())


def sweep_edge(test_hit, lo, hi, step):
    """Scan v = lo, lo+step ... for the first value where test_hit(v) is True; refine by bisection. None when never hit."""
    v = lo
    prev = None
    while v <= hi + 1e-9:
        if test_hit(v):
            if prev is None:
                return lo
            a, b = prev, v
            for _ in range(24):
                mid = 0.5 * (a + b)
                if test_hit(mid):
                    b = mid
                else:
                    a = mid
            return 0.5 * (a + b)
        prev = v
        v += step
    return None


def entry_measurements(ctx):
    """Arch (Entry_arch_band opening) and portal (clear to the lobby back wall) sizes by ray sweeps."""
    res = {}
    band = "Entry_arch_band"
    y0 = -100.0

    def band_hit(x, z):
        return ctx.first_hit((x, y0, z), only=band) is not None

    def free(x, z):  # portal clear: the first hit over everything is the lobby back wall
        h = ctx.first_hit((x, y0, z))
        return h is not None and h[1].startswith(LOBBY_BACK_PREFIX)

    if band in ctx.trees:
        for tag, zz in (("z0.1", 0.1), ("z1.0", 1.0), ("z3.0", 3.0)):
            r = sweep_edge(lambda x: band_hit(x, zz), 0.0, 14.0, 0.05)
            l = sweep_edge(lambda x: band_hit(-x, zz), 0.0, 14.0, 0.05)
            res["arch_half_r_" + tag] = r
            res["arch_half_l_" + tag] = l
        res["arch_clear_height"] = sweep_edge(lambda z: band_hit(0.0, z), 0.1, 30.0, 0.05)
    # portal: free test, so scan for the first NOT free value
    def first_blocked(test_blocked, lo, hi, step):
        return sweep_edge(test_blocked, lo, hi, step)
    if any(n.startswith(LOBBY_BACK_PREFIX) for n in ctx.trees):
        for tag, zz in (("z2.0", 2.0),):
            if free(0.0, zz):
                res["portal_half_r"] = first_blocked(lambda x: not free(x, zz), 0.0, 12.0, 0.05)
                res["portal_half_l"] = first_blocked(lambda x: not free(-x, zz), 0.0, 12.0, 0.05)
        if free(0.0, 0.2):
            res["portal_clear_height"] = first_blocked(lambda z: not free(0.0, z), 0.2, 12.0, 0.05)
    return res


def check_targets(ctx):
    items = []
    # overall bounds
    b = ctx.bounds()
    if b is None:
        return [item("targets.bounds", "overall bounds", "fail", "no mesh geometry")]
    lo, hi = b
    tb = TOL["bounds"]
    items.append(cmp_item("targets.bounds.xmax", "overall bounds +X (R06: +80)", float(hi[0]), 80.0, tb))
    items.append(cmp_item("targets.bounds.xmin", "overall bounds -X (R06: -80)", float(lo[0]), -80.0, tb))
    items.append(cmp_item("targets.bounds.ymax", "overall bounds +Y (R06: +60)", float(hi[1]), 60.0, tb))
    items.append(cmp_item("targets.bounds.ymin", "overall bounds -Y (R06: -60)", float(lo[1]), -60.0, tb))
    items.append(cmp_item("targets.bounds.ztop", "overall top z (R06: 240.0)", float(hi[2]), T["HEIGHT"], tb))
    items.append(cmp_item("targets.bounds.zbottom", "foundation bottom z (R06: -1.2)", float(lo[2]), T["FOUNDATION_BOTTOM"], tb))
    top_ob = max(ctx.geo, key=lambda n: ctx.geo[n].hi[2])
    items.append(item("targets.bounds.top_object", "object that sets the top", "info", "%s (z=%.3f)" % (top_ob, ctx.geo[top_ob].hi[2]),
                      baseline=False))
    # foundation
    g = ctx.geo.get("Podium_Foundation")
    if g is not None:
        items.append(cmp_item("targets.foundation.w", "Podium_Foundation width (160)", float(g.hi[0] - g.lo[0]), T["FOUNDATION"][0], tb))
        items.append(cmp_item("targets.foundation.d", "Podium_Foundation depth (120)", float(g.hi[1] - g.lo[1]), T["FOUNDATION"][1], tb))
    else:
        items.append(item("targets.foundation", "Podium_Foundation", "fail", "object not found"))
    # decks
    for i, (zt, w, d) in enumerate(T["DECKS"], start=1):
        nm = "Podium_Slab_T%d" % i
        g = ctx.geo.get(nm)
        if g is None:
            cand = [n for n in ctx.geo if re.match(r"^Podium_Slab", n) and n.endswith(str(i))]
            g = ctx.geo.get(cand[0]) if cand else None
            nm = cand[0] if cand else nm
        if g is None:
            items.append(item("targets.deck%d" % i, "deck %d slab" % i, "fail", "slab object not found", objects=[nm]))
            continue
        items.append(cmp_item("targets.deck%d.top" % i, "%s top z (%g)" % (nm, zt), float(g.hi[2]), zt, TOL["deck_z"], objects=[nm]))
        items.append(cmp_item("targets.deck%d.w" % i, "%s footprint X (%g)" % (nm, w), float(g.hi[0] - g.lo[0]), w, TOL["deck_xy"],
                              objects=[nm], detail="x %.2f..%.2f" % (g.lo[0], g.hi[0])))
        dep = float(g.hi[1] - g.lo[1])
        short = d / 2 + float(g.lo[1])  # front edge setback from -d/2
        extra = "y %.2f..%.2f; rear edge target %+.1f, front edge target %.1f (front edge %.2f m inside the R06 footprint)" % (
            g.lo[1], g.hi[1], d / 2, -d / 2, short)
        items.append(cmp_item("targets.deck%d.d" % i, "%s footprint Y (%g)" % (nm, d), dep, d, TOL["deck_xy"], objects=[nm], detail=extra))
    # tower glass at z=54 and roof
    skin = ctx.geo.get("Tower_curtainwall_skin")
    if skin is not None:
        m = skin.co[:, 2] <= T["DECKS"][-1][0] + 0.05
        ring = skin.co[m]
        w = float(ring[:, 0].max() - ring[:, 0].min())
        d = float(ring[:, 1].max() - ring[:, 1].min())
        items.append(cmp_item("targets.tower.glass_w", "tower glass width at z=54 (68, skin ring)", w, T["TOWER_BASE"][0], TOL["tower_glass"],
                              objects=["Tower_curtainwall_skin"], detail="%d ring verts at z<=54.05" % m.sum()))
        items.append(cmp_item("targets.tower.glass_d", "tower glass depth at z=54 (54, skin ring)", d, T["TOWER_BASE"][1], TOL["tower_glass"],
                              objects=["Tower_curtainwall_skin"]))
        pts = [ring]
        for nm in ("Tower_mullions", "Tower_storey_bands"):
            gg = ctx.geo.get(nm)
            if gg is not None:
                mm = (gg.co[:, 2] <= 55.0)
                if mm.any():
                    pts.append(gg.co[mm])
        allp = np.vstack(pts)
        items.append(cmp_item("targets.tower.bulge_w", "tower width at z=54..55 incl. mullions/bands bulge", float(np.ptp(allp[:, 0])),
                              T["TOWER_BASE"][0], TOL["tower_glass"]))
        items.append(cmp_item("targets.tower.bulge_d", "tower depth at z=54..55 incl. mullions/bands bulge", float(np.ptp(allp[:, 1])),
                              T["TOWER_BASE"][1], TOL["tower_glass"]))
        items.append(cmp_item("targets.tower.skin_top", "tower skin top z (216)", float(skin.hi[2]), T["TOWER_ROOF_Z"], TOL["roof_z"],
                              objects=["Tower_curtainwall_skin"]))
        items.append(cmp_item("targets.tower.skin_bottom", "tower skin bottom z (54)", float(skin.lo[2]), 54.0, TOL["roof_z"],
                              objects=["Tower_curtainwall_skin"]))
    else:
        items.append(item("targets.tower.glass", "Tower_curtainwall_skin", "fail", "object not found"))
    rp = ctx.geo.get("Tower_roof_plate")
    if rp is not None:
        items.append(cmp_item("targets.tower.roof_top", "roof plate top z (216)", float(rp.hi[2]), T["TOWER_ROOF_Z"], TOL["roof_z"],
                              objects=["Tower_roof_plate"]))
    else:
        items.append(item("targets.tower.roof_top", "Tower_roof_plate top z", "fail", "object not found"))
    tp = ctx.geo.get("Tower_roof_parapet")
    if tp is not None:
        items.append(item("targets.tower.parapet_top", "roof parapet top z (above the 216 roof line)", "info",
                          "%.2f m" % tp.hi[2], float(tp.hi[2]), unit="m", baseline=False))
    # rib tips
    for rid, (foot, tip, tz) in T["RIBS"].items():
        nm = "Rib_" + rid
        g = ctx.geo.get(nm)
        if g is None:
            items.append(item("targets.rib.%s" % rid, "%s tip" % nm, "fail", "object not found", objects=[nm]))
            continue
        tpt, n = tip_of(g)
        dx, dy, dz = tpt[0] - tip[0], tpt[1] - tip[1], tpt[2] - tz
        ok = max(abs(dx), abs(dy), abs(dz)) <= TOL["rib_tip"] + 1e-9
        items.append(item("targets.rib.%s.tip" % rid, "%s tip x,y,z -> (%g, %g, %g)" % (nm, tip[0], tip[1], tz),
                          "pass" if ok else "fail",
                          "measured (%.3f, %.3f, %.3f), delta (%+.3f, %+.3f, %+.3f), tol +/-%g, %d apex vertices" % (
                              tpt[0], tpt[1], tpt[2], dx, dy, dz, TOL["rib_tip"], n),
                          [round(float(v), 4) for v in tpt], [tip[0], tip[1], tz], TOL["rib_tip"], "m", [nm]))
        ft = g.co[g.co[:, 2] <= g.lo[2] + 0.05]
        fc = ft.mean(axis=0)
        dist = math.hypot(fc[0] - foot[0], fc[1] - foot[1])
        items.append(item("targets.rib.%s.foot" % rid, "%s foot centroid vs C.RIBS foot (%g, %g)" % (nm, foot[0], foot[1]), "info",
                          "foot centroid (%.2f, %.2f) at z=%.2f, %.2f m from the nominal foot (not gated)" % (fc[0], fc[1], g.lo[2], dist),
                          round(float(dist), 3), unit="m", objects=[nm], baseline=False))
    # entry arch / portal
    em = entry_measurements(ctx)
    ctx.extra["entry_measure"] = em

    def pair_width(prefix, tag):
        a, c = em.get("%s_r_%s" % (prefix, tag)), em.get("%s_l_%s" % (prefix, tag))
        return (a + c) if a is not None and c is not None else None
    aw = pair_width("arch_half", "z0.1")
    items.append(cmp_item("targets.entry.arch_w", "entry arch clear width at springing z=0.1 (18, Entry_arch_band)", aw,
                          T["ENTRY_ARCH"][0], TOL["entry"], objects=["Entry_arch_band"]))
    items.append(cmp_item("targets.entry.arch_h", "entry arch clear height at x=0 (14, Entry_arch_band)", em.get("arch_clear_height"),
                          T["ENTRY_ARCH"][1], TOL["entry"], objects=["Entry_arch_band"]))
    pw = None
    if em.get("portal_half_r") is not None and em.get("portal_half_l") is not None:
        pw = em["portal_half_r"] + em["portal_half_l"]
    items.append(cmp_item("targets.entry.portal_w", "portal clear width at z=2.0 (8, first hit = lobby back wall)", pw,
                          T["ENTRY_PORTAL"][0], TOL["entry"]))
    items.append(cmp_item("targets.entry.portal_h", "portal clear height at x=0 (4.5, first hit = lobby back wall)",
                          em.get("portal_clear_height"), T["ENTRY_PORTAL"][1], TOL["entry"]))
    return items


# ------------------------------------------------------------------ 3. mesh health ----------------------------
def label_components(nv, e0, e1):
    labels = np.arange(nv)
    if len(e0) == 0:
        return labels
    for _ in range(100000):
        l0, l1 = labels[e0], labels[e1]
        m = np.minimum(l0, l1)
        new = labels.copy()
        np.minimum.at(new, l0, m)
        np.minimum.at(new, l1, m)
        for _ in range(8):
            new = new[new]
        if np.array_equal(new, labels):
            break
        labels = new
    return labels


def health_of(g):
    h = {}
    nv, ne, npoly, nl = g.nv, g.ne, g.npoly, g.nl
    e = g.edges
    used = np.bincount(g.le, minlength=ne) if nl else np.zeros(ne, int)
    in_edge = np.zeros(nv, bool)
    if ne:
        in_edge[e.ravel()] = True
    h["verts"], h["faces"], h["tris"], h["edges"] = nv, npoly, g.nt, ne
    h["ngons"] = int((g.pt > 4).sum()) if npoly else 0
    h["loose_verts"] = int((~in_edge).sum())
    h["loose_edges"] = int((used == 0).sum())
    h["boundary_edges"] = int((used == 1).sum())
    h["nonmanifold_edges"] = int((used > 2).sum())
    lens = np.linalg.norm(g.co[e[:, 0]] - g.co[e[:, 1]], axis=1) if ne else np.zeros(0)
    h["zero_len_edges"] = int((lens < TOL["edge_eps"]).sum())
    h["degenerate_faces"] = int((g.area < TOL["area_eps"]).sum()) if npoly else 0
    if nv:
        q = np.round(g.co / TOL["dup_grid"]).astype(np.int64)
        h["duplicate_verts"] = int(nv - len(np.unique(q, axis=0)))
    else:
        h["duplicate_verts"] = 0
    # winding consistency across manifold edges
    if nl:
        nxt = np.arange(nl) + 1
        nxt[g.ps + g.pt - 1] = g.ps
        vf, vt = g.lv, g.lv[nxt]
        s = np.bincount(g.le, weights=np.where(vf < vt, 1.0, -1.0), minlength=ne)
        bad_wind = (used == 2) & (np.abs(s) > 0.5)
    else:
        bad_wind = np.zeros(ne, bool)
    h["inconsistent_edges"] = int(bad_wind.sum())
    # components (by faces)
    face_edge = used > 0
    labels = label_components(nv, e[face_edge, 0], e[face_edge, 1]) if ne else np.arange(nv)
    face_verts = np.unique(g.lv) if nl else np.zeros(0, int)
    comp_ids = np.unique(labels[face_verts]) if len(face_verts) else np.zeros(0, int)
    open_edge = (used == 1) | (used > 2)
    open_comp = np.zeros(nv, bool)
    if open_edge.any():
        open_comp[labels[e[open_edge, 0]]] = True
    wind_comp = np.zeros(nv, bool)
    if bad_wind.any():
        wind_comp[labels[e[bad_wind, 0]]] = True

    def box(pts):
        return None if len(pts) == 0 else [round(float(v), 2) for v in list(pts.min(axis=0)) + list(pts.max(axis=0))]
    h["loose_bbox"] = box(g.co[~in_edge]) if h["loose_verts"] else None
    h["wind_bbox"] = box(g.co[e[bad_wind].ravel()]) if bad_wind.any() else None
    h["degenerate_bbox"] = box(g.co[g.lv[np.concatenate([np.arange(s0, s0 + n0) for s0, n0 in zip(g.ps[g.area < TOL["area_eps"]], g.pt[g.area < TOL["area_eps"]])])]])         if h["degenerate_faces"] else None
    if g.nt:
        c0 = g.co - g.co.mean(axis=0)
        a, b, c = c0[g.tv[:, 0]], c0[g.tv[:, 1]], c0[g.tv[:, 2]]
        vol_t = np.einsum("ij,ij->i", a, np.cross(b, c)) / 6.0
        vol = np.bincount(labels[g.tv[:, 0]], weights=vol_t, minlength=nv)
    else:
        vol = np.zeros(nv)
    closed_ids = [i for i in comp_ids if not open_comp[i]]
    consistent_ids = [i for i in closed_ids if not wind_comp[i]]
    h["components"] = int(len(comp_ids))
    h["closed_components"] = int(len(closed_ids))
    h["open_components"] = int(len(comp_ids) - len(closed_ids))
    h["inconsistent_components"] = int(len([i for i in closed_ids if wind_comp[i]]))
    inv = [i for i in consistent_ids if vol[i] < -1e-6]
    zero = [i for i in consistent_ids if abs(vol[i]) <= 1e-6]
    h["inverted_components"] = int(len(inv))
    h["zero_volume_closed"] = int(len(zero))
    h["closed_volume_m3"] = round(float(sum(vol[i] for i in consistent_ids)), 3)
    h["inverted_volume_m3"] = round(float(sum(vol[i] for i in inv)), 3)
    if h["open_components"] == 0 and h["closed_components"] > 0:
        h["class"] = "closed"
    elif h["closed_components"] == 0:
        h["class"] = "open"
    else:
        h["class"] = "mixed"
    # orientation heuristic for open shells: share of mostly-vertical faces whose normal points away from the object axis
    h["outward_frac"] = None
    if h["open_components"] > 0 and npoly:
        fm = np.abs(g.normal[:, 2]) < 0.7
        ext = g.hi - g.lo
        if fm.sum() >= 50 and ext[0] > 5.0 and ext[1] > 5.0:
            ctr = 0.5 * (g.lo + g.hi)
            rad = g.center[fm, :2] - ctr[:2]
            dots = np.einsum("ij,ij->i", rad, g.normal[fm, :2])
            h["outward_frac"] = round(float((dots > 0).mean()), 3)
    return h


def check_health(ctx):
    items = []
    per = {}
    for n, g in ctx.geo.items():
        try:
            per[n] = health_of(g)
            per[n]["collection"] = ctx.coll.get(n)
        except Exception as e:
            per[n] = dict(error=repr(e), collection=ctx.coll.get(n))
    ctx.extra["health"] = per
    errs = [n for n, h in per.items() if "error" in h]
    if errs:
        items.append(item("health.errors", "health analysis errors", "fail", "%d objects could not be analysed" % len(errs),
                          len(errs), 0, unit="count", objects=["%s: %s" % (n, per[n]["error"]) for n in errs]))
    ok = {n: h for n, h in per.items() if "error" not in h}

    WHERE = {"loose_verts": "loose_bbox", "inconsistent_edges": "wind_bbox", "degenerate_faces": "degenerate_bbox"}

    def listing(key, flt=None):
        rows = []
        for n, h in ok.items():
            if h[key] > 0 and (flt is None or flt(h)):
                w = h.get(WHERE.get(key, ""), None)
                rows.append((h[key], "%s: %s=%s%s" % (n, key, h[key], (" at [x %.1f..%.1f, y %.1f..%.1f, z %.1f..%.1f]" % (
                    w[0], w[3], w[1], w[4], w[2], w[5])) if w else "")))
        return [r[1] for r in sorted(rows, key=lambda r: -r[0])]

    def agg(iid, title, key, status_if, what):
        lst = listing(key)
        tot = sum(h[key] for h in ok.values())
        items.append(item(iid, title, status_if if lst else "pass",
                          ("%d %s across %d objects" % (tot, what, len(lst))) if lst else "none in %d objects" % len(ok),
                          tot, 0, unit="count", objects=lst or None))
    agg("health.loose_verts", "loose vertices (not in any edge)", "loose_verts", "fail", "loose vertices")
    agg("health.loose_edges", "loose/wire edges (no face)", "loose_edges", "fail", "wire edges")
    agg("health.degenerate_faces", "degenerate zero-area faces (< %g m2)" % TOL["area_eps"], "degenerate_faces", "fail", "degenerate faces")
    agg("health.zero_len_edges", "zero-length edges (< %g m)" % TOL["edge_eps"], "zero_len_edges", "warn", "zero-length edges")
    agg("health.nonmanifold", "non-manifold edges (shared by more than 2 faces)", "nonmanifold_edges", "fail", "edges with >2 faces")
    agg("health.inconsistent_winding", "inconsistent face winding (flipped neighbours)", "inconsistent_edges", "fail", "edges between faces wound opposite ways")
    agg("health.inverted_closed", "inverted normals on closed shells (negative signed volume)", "inverted_components", "fail", "inverted closed shells")
    agg("health.zero_volume_closed", "closed shells with ~0 volume", "zero_volume_closed", "warn", "flat closed shells")
    agg("health.duplicate_verts", "duplicate (unwelded, coincident within %g m) vertices" % TOL["dup_grid"], "duplicate_verts", "warn", "duplicate vertices")
    # open shells: documented warn
    open_objs = [(n, h) for n, h in ok.items() if h["class"] in ("open", "mixed")]
    closed_objs = [n for n, h in ok.items() if h["class"] == "closed"]
    by_coll = {}
    for n, h in open_objs:
        by_coll.setdefault(h["collection"], []).append(n)
    items.append(item("health.open_shells", "open surfaces / zero-thickness shells (documented: thin shells, hollow-ready)",
                      "warn" if open_objs else "pass",
                      "%d of %d objects are open or mixed shells (%d fully closed). Open boundary edges are by design for skin, bands, "
                      "walls and glazing; per collection: %s" % (len(open_objs), len(ok), len(closed_objs),
                                                                 ", ".join("%s=%d" % (c, len(v)) for c, v in sorted(by_coll.items()))),
                      len(open_objs), unit="count", baseline=True,
                      objects=sorted("%s [%s, %d boundary edges]" % (n, h["class"], h["boundary_edges"]) for n, h in open_objs) or None))
    items.append(item("health.closed_shells", "fully closed solid objects", "info",
                      "%d objects: %s" % (len(closed_objs), ", ".join(sorted(closed_objs)[:12]) + (" ..." if len(closed_objs) > 12 else "")),
                      len(closed_objs), unit="count", baseline=False))
    # orientation heuristic on open shells
    flagged = sorted("%s: %.0f%% outward" % (n, 100 * h["outward_frac"]) for n, h in ok.items()
                     if h["outward_frac"] is not None and h["outward_frac"] < 0.25)
    items.append(item("health.open_shell_orientation",
                      "open shells: wall normals face away from the object axis (heuristic; <25% outward is flagged)",
                      "warn" if flagged else "pass",
                      ("%d open shells have mostly inward-facing wall normals (could be inverted, or a hollow wrapper seen from inside)" % len(flagged)) if flagged
                      else "no open shell is predominantly inward-facing", len(flagged), 0, unit="count", objects=flagged or None))
    # face count outliers
    names = sorted(ok)
    fc = np.array([max(ok[n]["faces"], 1) for n in names], dtype=float)
    lg = np.log10(fc)
    med = float(np.median(lg))
    mad = float(np.median(np.abs(lg - med)))
    hi_out, lo_out = [], []
    if mad > 0:
        mz = 0.6745 * (lg - med) / mad
        for n, z in zip(names, mz):
            if z > 3.5:
                hi_out.append("%s: %d faces (z=%.1f)" % (n, ok[n]["faces"], z))
            elif z < -3.5:
                lo_out.append("%s: %d faces (z=%.1f)" % (n, ok[n]["faces"], z))
    items.append(item("health.face_outliers_high", "face-count outliers, heavy (robust z > 3.5 on log10 faces; median %d)" % round(10 ** med),
                      "warn" if hi_out else "pass", "%d heavy outliers" % len(hi_out) if hi_out else "none",
                      len(hi_out), 0, unit="count", objects=hi_out or None, baseline=False))
    items.append(item("health.face_outliers_low", "face-count outliers, tiny (robust z < -3.5)", "info" if lo_out else "pass",
                      "%d very light objects" % len(lo_out) if lo_out else "none", len(lo_out), unit="count", objects=lo_out or None, baseline=False))
    items.append(item("health.ngons", "n-gon (>4 sides) face count", "info",
                      "%d n-gons in %d objects" % (sum(h["ngons"] for h in ok.values()), sum(1 for h in ok.values() if h["ngons"])),
                      sum(h["ngons"] for h in ok.values()), unit="count",
                      objects=sorted("%s: %d" % (n, h["ngons"]) for n, h in ok.items() if h["ngons"]) or None, baseline=False))
    items.append(item("health.totals", "totals", "info",
                      "verts %d, faces %d, triangles %d" % (sum(h["verts"] for h in ok.values()), sum(h["faces"] for h in ok.values()),
                                                           sum(h["tris"] for h in ok.values())),
                      sum(h["tris"] for h in ok.values()), unit="tris"))
    # the per-object table travels in the check data
    items[-1]["data"] = per
    return items


# ------------------------------------------------------------------ 4. interference ---------------------------
def check_interference(ctx):
    items = []
    by_coll = {c: [n for n in ctx.tnames if ctx.coll.get(n) == c] for c in EXPECTED_COLLECTIONS}
    pad = 1e-4
    for ca, cb, required in INTERFERENCE_PAIRS:
        rows = []
        tot = 0
        opairs = 0
        tested = 0
        for a in by_coll.get(ca, []):
            ga = ctx.geo[a]
            for b in by_coll.get(cb, []):
                gb = ctx.geo[b]
                if np.any(ga.hi + pad < gb.lo) or np.any(gb.hi + pad < ga.lo):
                    continue
                tested += 1
                ov = ctx.trees[a].overlap(ctx.trees[b])
                if ov:
                    rows.append((a, b, len(ov)))
                    tot += len(ov)
                    opairs += 1
        rows.sort(key=lambda r: -r[2])
        top = ["%s x %s: %d" % r for r in rows[:8]]
        iid = "interference.%s-%s" % (ca, cb)
        title = "%s vs %s overlapping triangle pairs%s" % (ca, cb, " (REQUIRED = 0)" if required else "")
        if required:
            st = "fail" if tot else "pass"
        else:
            st = "info"
        det = "%d triangle pairs over %d object pairs (%d bbox-overlapping pairs tested)" % (tot, opairs, tested)
        if top and not required:
            det += "; top: " + "; ".join(top[:3])
        items.append(item(iid, title, st, det, tot, 0 if required else None, unit="tri pairs",
                          objects=top or None, data=dict(object_pairs=opairs, tested=tested, top=[list(r) for r in rows[:25]])))
    return items


# ------------------------------------------------------------------ 5. entry opening --------------------------
def check_entry(ctx):
    items = []
    if not any(n.startswith(LOBBY_BACK_PREFIX) for n in ctx.trees):
        return [item("entry.setup", "Entry_lobby_back_* objects", "fail", "no Entry_lobby_back_* object in the model")]
    all_rows = []
    for z in RAY_Z:
        rows, bad = [], []
        for x in RAY_X:
            h = ctx.first_hit((x, -100.0, z))
            name = h[1] if h else None
            hy = round(h[2].y, 3) if h else None
            ok = bool(name) and name.startswith(LOBBY_BACK_PREFIX)
            rows.append(dict(x=x, z=z, hit=name, hit_y=hy, ok=ok))
            if not ok:
                bad.append("x=%g: hit %s at y=%s" % (x, name, hy))
        all_rows += rows
        hit_names = sorted({r["hit"] for r in rows if r["hit"]})
        ys = sorted({r["hit_y"] for r in rows if r["hit_y"] is not None})
        items.append(item("entry.ray.z%.1f" % z, "rays +Y from y=-100 at z=%.1f, x=-4..4 step 2: first hit is Entry_lobby_back_*" % z,
                          "fail" if bad else "pass",
                          ("%d of %d rays blocked" % (len(bad), len(rows))) if bad else
                          "5 of 5 rays reach %s at y=%s" % (", ".join(hit_names), ", ".join(str(y) for y in ys)),
                          sum(1 for r in rows if r["ok"]), len(rows), unit="rays", objects=bad or None, data=rows))
    okn = sum(1 for r in all_rows if r["ok"])
    items.append(item("entry.ray.total", "all entry rays reach the lobby back wall", "pass" if okn == len(all_rows) else "fail",
                      "%d of %d rays" % (okn, len(all_rows)), okn, len(all_rows), unit="rays"))
    em = ctx.extra.get("entry_measure") or entry_measurements(ctx)
    ctx.extra["entry_measure"] = em
    lines = []

    def lr(k):
        a, c = em.get("%s_r_%s" % (k[0], k[1])), em.get("%s_l_%s" % (k[0], k[1]))
        return a, c
    for tag, zz in (("z0.1", 0.1), ("z1.0", 1.0), ("z3.0", 3.0)):
        a, c = lr(("arch_half", tag))
        if a is not None and c is not None:
            lines.append("z=%.1f: right %.3f / left %.3f = %.3f" % (zz, a, c, a + c))
            items.append(item("entry.arch_width_%s" % tag, "arch clear width at z=%.1f (horizontal sweep, Entry_arch_band)" % zz, "info",
                              "right half %.3f m, left half %.3f m, width %.3f m" % (a, c, a + c), round(a + c, 3), unit="m"))
    items.append(item("entry.arch_height", "arch clear height at x=0 (vertical sweep, Entry_arch_band)", "info",
                      "%s m" % f(em.get("arch_clear_height")), em.get("arch_clear_height"), unit="m"))
    pr, pl = em.get("portal_half_r"), em.get("portal_half_l")
    items.append(item("entry.portal_width", "portal clear width at z=2.0 (horizontal sweep, first hit must be lobby back wall)", "info",
                      "right %s, left %s, width %s m" % (f(pr), f(pl), f(pr + pl if pr is not None and pl is not None else None)),
                      round(pr + pl, 3) if pr is not None and pl is not None else None, unit="m"))
    items.append(item("entry.portal_height", "portal clear height at x=0 (vertical sweep, first hit must be lobby back wall)", "info",
                      "%s m" % f(em.get("portal_clear_height")), em.get("portal_clear_height"), unit="m"))
    # symmetry
    if pr is not None and pl is not None:
        items.append(item("entry.portal_symmetry", "portal left/right clear halves match (0.1 m)", "pass" if abs(pr - pl) <= 0.1 else "warn",
                          "right %.3f vs left %.3f" % (pr, pl), round(abs(pr - pl), 3), 0.1, unit="m"))
    return items


# ------------------------------------------------------------------ 6. export round trip ----------------------
def read_glb_json(path):
    with open(path, "rb") as fh:
        head = fh.read(12)
        magic, ver, length = struct.unpack("<4sII", head)
        clen, ctype = struct.unpack("<I4s", fh.read(8))
        return json.loads(fh.read(clen).decode("utf8")), ver, length


def scene_snapshot(ctx_names=None):
    """Mesh object name -> dict(tris, lo, hi) from the CURRENT scene (world space)."""
    dg = bpy.context.evaluated_depsgraph_get()
    out = {}
    for ob in bpy.data.objects:
        if ob.type != "MESH":
            continue
        ev = ob.evaluated_get(dg)
        me = ev.to_mesh()
        try:
            nv = len(me.vertices)
            if nv == 0:
                out[ob.name] = dict(tris=0, lo=None, hi=None)
                continue
            co = np.empty(nv * 3, np.float32)
            me.vertices.foreach_get("co", co)
            M = np.array(ob.matrix_world, dtype=np.float64)
            w = co.reshape(nv, 3).astype(np.float64) @ M[:3, :3].T + M[:3, 3]
            me.calc_loop_triangles()
            out[ob.name] = dict(tris=len(me.loop_triangles), lo=w.min(axis=0), hi=w.max(axis=0))
        finally:
            ev.to_mesh_clear()
    return out


def check_export(ctx):
    items = []
    if ctx.args["skip_export"]:
        return [item("export.skipped", "glTF export round-trip", "info", "skipped with --skip-export", baseline=False)]
    stem = os.path.splitext(os.path.basename(bpy.data.filepath or "model"))[0]
    glb = os.path.join(ctx.args["out"], stem + "_qa.glb")
    if os.path.exists(glb):
        os.remove(glb)
    before = {n: dict(tris=g.nt, lo=g.lo, hi=g.hi) for n, g in ctx.geo.items()}
    blo, bhi = ctx.bounds()
    t0 = time.time()
    try:
        bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB")
    except Exception as e:
        return [item("export.write", "export glTF binary (Blender defaults)", "fail", "export failed: " + repr(e))]
    if not os.path.exists(glb):
        return [item("export.write", "export glTF binary (Blender defaults)", "fail", "export reported no error but no file was written")]
    size = os.path.getsize(glb)
    mib = size / 1048576.0
    items.append(item("export.write", "export glTF binary (Blender defaults, no extra transforms)", "pass",
                      "wrote %s in %.1f s" % (glb, time.time() - t0), size, unit="bytes", baseline=False))
    items.append(item("export.size", "GLB size vs the repo served-file guidance of 25 MiB (info only)", "info",
                      "%.2f MiB (%d bytes); %.0f%% of the 25 MiB guidance%s" % (mib, size, 100 * size / GLB_LIMIT_BYTES,
                                                                                   " - OVER the guidance" if size > GLB_LIMIT_BYTES else ""),
                      round(mib, 3), 25.0, unit="MiB", baseline=False))
    gj = None
    try:
        gj, ver, ln = read_glb_json(glb)
        prims = sum(len(m.get("primitives", [])) for m in gj.get("meshes", []))
        items.append(item("export.glb_content", "GLB content (parsed header JSON)", "info",
                          "glTF %s; nodes %d, meshes %d, primitives %d, materials %d, accessors %d; extensions used: %s" % (
                              ver, len(gj.get("nodes", [])), len(gj.get("meshes", [])), prims, len(gj.get("materials", [])),
                              len(gj.get("accessors", [])), ", ".join(gj.get("extensionsUsed", [])) or "none"),
                          len(gj.get("nodes", [])), unit="nodes", baseline=False))
        ctx.extra["glb_nodes"] = len(gj.get("nodes", []))
    except Exception as e:
        items.append(item("export.glb_content", "GLB header parse", "warn", "could not parse: " + repr(e), baseline=False))
    ctx.extra["glb_bytes"] = size
    # --- re-import into an empty scene (replaces the loaded model; all later checks use cached data only) ---
    try:
        bpy.ops.wm.read_factory_settings(use_empty=True)
        bpy.ops.import_scene.gltf(filepath=glb)
    except Exception as e:
        items.append(item("export.import", "re-import GLB into an empty scene", "fail", "import failed: " + repr(e)))
        return items
    after_raw = scene_snapshot()
    after = {}
    for n, d in after_raw.items():
        base = re.sub(r"\.\d{3}$", "", n)
        after[n if n in before else base] = d
    nb, na = len(before), len(after_raw)
    items.append(item("export.object_count", "mesh object count after round trip", "pass" if na == nb else "fail",
                      "original %d, re-imported %d" % (nb, na), na, nb, unit="count"))
    lost = sorted(n for n in before if n not in after)
    extra = sorted(n for n in after if n not in before)
    items.append(item("export.lost", "objects lost in the round trip (name not found after re-import)", "fail" if lost else "pass",
                      "%d lost" % len(lost) if lost else "none", len(lost), 0, unit="count", objects=lost or None))
    items.append(item("export.extra", "unexpected extra mesh objects after re-import", "warn" if extra else "pass",
                      "%d extra" % len(extra) if extra else "none", len(extra), 0, unit="count", objects=extra or None))
    merged = na < nb and not lost
    items.append(item("export.merged", "objects merged by the exporter/importer", "fail" if merged else "pass",
                      "fewer objects than the original with no names missing" if merged else "none detected", baseline=False))
    # tris per object
    tdiff = []
    bdiff = []
    for n, d in before.items():
        a = after.get(n)
        if a is None:
            continue
        if a["tris"] != d["tris"]:
            tdiff.append("%s: %d -> %d tris" % (n, d["tris"], a["tris"]))
        if a["lo"] is not None:
            dev = max(float(np.abs(a["lo"] - d["lo"]).max()), float(np.abs(a["hi"] - d["hi"]).max()))
            if dev > TOL["glb_bounds"]:
                bdiff.append("%s: bbox deviates %.3f m" % (n, dev))
    items.append(item("export.tris", "triangle count per object after round trip", "fail" if tdiff else "pass",
                      "%d objects changed" % len(tdiff) if tdiff else "all match (original %d, re-imported %d triangles)" % (
                          sum(d["tris"] for d in before.values()), sum(d["tris"] for d in after_raw.values())),
                      sum(d["tris"] for d in after_raw.values()), sum(d["tris"] for d in before.values()), unit="tris",
                      objects=tdiff or None))
    items.append(item("export.object_bounds", "per-object bounds after round trip (tol %.2f m)" % TOL["glb_bounds"], "fail" if bdiff else "pass",
                      "%d objects deviate" % len(bdiff) if bdiff else "all %d matched objects within tolerance" % (nb - len(lost)),
                      len(bdiff), 0, unit="count", objects=bdiff or None))
    los = [d["lo"] for d in after_raw.values() if d["lo"] is not None]
    his = [d["hi"] for d in after_raw.values() if d["hi"] is not None]
    if los:
        alo, ahi = np.min(los, axis=0), np.max(his, axis=0)
        dev = max(float(np.abs(alo - blo).max()), float(np.abs(ahi - bhi).max()))
        items.append(item("export.bounds", "overall bounds after round trip (tol %.2f m)" % TOL["glb_bounds"],
                          "pass" if dev <= TOL["glb_bounds"] else "fail",
                          "original %s..%s ; re-imported %s..%s ; max deviation %.4f m" % (
                              [round(float(v), 3) for v in blo], [round(float(v), 3) for v in bhi],
                              [round(float(v), 3) for v in alo], [round(float(v), 3) for v in ahi], dev),
                          round(dev, 4), TOL["glb_bounds"], unit="m", baseline=False))
    else:
        items.append(item("export.bounds", "overall bounds after round trip", "fail", "no mesh geometry after re-import"))
    if ctx.args["delete_glb"]:
        try:
            os.remove(glb)
        except Exception:
            pass
    return items


# ------------------------------------------------------------------ 7. regression ------------------------------
STATUS_RANK = {"pass": 0, "info": 0, "warn": 1, "fail": 2}


def make_baseline(ctx, results):
    b = ctx.bounds()
    objs = {n: dict(faces=g.npoly, tris=g.nt, bbox=[round(float(v), 3) for v in list(g.lo) + list(g.hi)]) for n, g in sorted(ctx.geo.items())}
    meas, stat = {}, {}
    for r in results:
        for it in r["items"]:
            if it["status"] in ("pass", "warn", "fail"):
                stat[it["id"]] = it["status"]
            if it.get("baseline") and isinstance(it.get("measured"), (int, float)) and not isinstance(it.get("measured"), bool):
                meas[it["id"]] = dict(v=round(float(it["measured"]), 4), u=it.get("unit"))
    return dict(schema=1, tool="qa_check", version=VERSION, blend=ctx.blend_name,
                generated_utc=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
                counts=dict(objects=len(ctx.geo),
                            faces=sum(g.npoly for g in ctx.geo.values()), triangles=sum(g.nt for g in ctx.geo.values()),
                            verts=sum(g.nv for g in ctx.geo.values()),
                            per_collection={c: sum(1 for n in ctx.geo if ctx.coll.get(n) == c) for c in EXPECTED_COLLECTIONS}),
                bounds=dict(min=[round(float(v), 3) for v in b[0]], max=[round(float(v), 3) for v in b[1]]) if b else None,
                glb_bytes=ctx.extra.get("glb_bytes"), measurements=meas, statuses=stat, objects=objs)


def diff_baseline(cur, base):
    items = []
    tol = TOL["baseline_m"]
    # counts
    ch = []
    for k in ("objects", "faces", "triangles", "verts"):
        a, c = base.get("counts", {}).get(k), cur["counts"].get(k)
        if a is None:
            continue
        rel = abs(c - a) / max(a, 1)
        if k == "objects" and c != a or k != "objects" and rel > 0.005:
            ch.append("%s: %s -> %s (%+d, %+.2f%%)" % (k, a, c, c - a, 100 * (c - a) / max(a, 1)))
    for cn in EXPECTED_COLLECTIONS:
        a, c = base.get("counts", {}).get("per_collection", {}).get(cn), cur["counts"]["per_collection"].get(cn)
        if a is not None and a != c:
            ch.append("collection %s objects: %s -> %s" % (cn, a, c))
    items.append(item("regression.counts", "object/face/triangle counts vs baseline (objects exact, mesh totals 0.5%)",
                      "warn" if ch else "pass", "; ".join(ch) if ch else "unchanged within tolerance", len(ch), 0, unit="count",
                      objects=ch or None, baseline=False))
    # bounds
    bb, cb = base.get("bounds"), cur.get("bounds")
    if bb and cb:
        dev = max(abs(np.array(bb["min"]) - np.array(cb["min"])).max(), abs(np.array(bb["max"]) - np.array(cb["max"])).max())
        items.append(item("regression.bounds", "overall bounds vs baseline (tol %.2f m)" % tol, "warn" if dev > tol else "pass",
                          "baseline %s..%s ; now %s..%s ; max deviation %.3f m" % (bb["min"], bb["max"], cb["min"], cb["max"], dev),
                          round(float(dev), 4), tol, unit="m", baseline=False))
    # measurements
    chg = []
    for k, bv in base.get("measurements", {}).items():
        cv = cur["measurements"].get(k)
        if cv is None:
            chg.append("%s: missing now (baseline %s)" % (k, bv["v"]))
            continue
        t = tol if bv.get("u") in ("m",) else 0.0
        if bv.get("u") == "MiB" or bv.get("u") == "bytes":
            t = 0.0 if bv.get("u") == "bytes" else tol
        if abs(cv["v"] - bv["v"]) > t + 1e-9:
            chg.append("%s: %g -> %g (%+.4g %s)" % (k, bv["v"], cv["v"], cv["v"] - bv["v"], bv.get("u") or ""))
    for k in cur["measurements"]:
        if k not in base.get("measurements", {}):
            chg.append("%s: new measurement (%s)" % (k, cur["measurements"][k]["v"]))
    items.append(item("regression.measurements", "key measurements vs baseline (m: %.2f tol, counts exact)" % tol,
                      "warn" if chg else "pass", "%d changed" % len(chg) if chg else "all %d unchanged" % len(cur["measurements"]),
                      len(chg), 0, unit="count", objects=chg or None, baseline=False))
    # objects
    bo, co = base.get("objects", {}), cur["objects"]
    added = sorted(set(co) - set(bo))
    removed = sorted(set(bo) - set(co))
    changed = []
    for n in sorted(set(co) & set(bo)):
        a, c = bo[n], co[n]
        probs = []
        if a["faces"] != c["faces"] and abs(a["faces"] - c["faces"]) > 0.01 * max(a["faces"], 1):
            probs.append("faces %d -> %d" % (a["faces"], c["faces"]))
        dev = max(abs(np.array(a["bbox"]) - np.array(c["bbox"])))
        if dev > tol:
            probs.append("bbox moved %.3f m" % dev)
        if probs:
            changed.append("%s: %s" % (n, "; ".join(probs)))
    lst = ["added: " + n for n in added] + ["removed: " + n for n in removed] + changed
    items.append(item("regression.objects", "per-object faces (1%%) and bounds (%.2f m) vs baseline" % tol, "warn" if lst else "pass",
                      "%d added, %d removed, %d changed" % (len(added), len(removed), len(changed)) if lst else "all %d objects unchanged" % len(co),
                      len(lst), 0, unit="count", objects=lst or None, baseline=False))
    # status regressions
    worse, better = [], []
    for k, s in cur["statuses"].items():
        b0 = base.get("statuses", {}).get(k)
        if b0 is None:
            continue
        if STATUS_RANK[s] > STATUS_RANK[b0]:
            worse.append("%s: %s -> %s" % (k, b0, s))
        elif STATUS_RANK[s] < STATUS_RANK[b0]:
            better.append("%s: %s -> %s" % (k, b0, s))
    items.append(item("regression.status", "check items that got worse since baseline", "fail" if worse else "pass",
                      "%d worse, %d better" % (len(worse), len(better)), len(worse), 0, unit="count",
                      objects=(worse + ["(better) " + x for x in better]) or None, baseline=False))
    return items


def check_regression(ctx):
    items = []
    cur = make_baseline(ctx, ctx.results)
    path = os.path.join(ctx.args["out"], "qa_baseline.json")
    try:
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(cur, fh, indent=1, default=json_default)
        items.append(item("regression.baseline_written", "qa_baseline.json written", "info", path, baseline=False))
    except Exception as e:
        items.append(item("regression.baseline_written", "qa_baseline.json written", "fail", "write failed: " + repr(e), baseline=False))
    bpath = ctx.args["baseline"]
    if not bpath:
        items.append(item("regression.diff", "diff against a previous baseline", "info", "no --baseline given; nothing to compare", baseline=False))
        return items
    try:
        with open(bpath, "r", encoding="utf-8") as fh:
            base = json.load(fh)
    except Exception as e:
        items.append(item("regression.load", "load --baseline file", "fail", "%s: %s" % (bpath, repr(e)), baseline=False))
        return items
    items.append(item("regression.compared", "baseline loaded", "info",
                      "%s (blend %s, generated %s)" % (bpath, base.get("blend"), base.get("generated_utc")), baseline=False))
    items += diff_baseline(cur, base)
    return items


# ------------------------------------------------------------------ reporting ---------------------------------
def json_default(o):
    if isinstance(o, (np.integer,)):
        return int(o)
    if isinstance(o, (np.floating,)):
        return None if not math.isfinite(float(o)) else float(o)
    if isinstance(o, np.ndarray):
        return o.tolist()
    if isinstance(o, (np.bool_,)):
        return bool(o)
    return str(o)


def file_sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def md_escape(s):
    return str(s).replace("|", "/").replace("\n", " ")


def build_markdown(rep):
    s = rep["summary"]
    L = []
    L.append("# Crown Landmark QA summary")
    L.append("")
    L.append("- Model: `%s`" % rep["blend"]["path"])
    L.append("- SHA-256: `%s` (%d bytes)" % (rep["blend"]["sha256"], rep["blend"]["size"]))
    L.append("- Blender %s, qa_check %s, %s, %.1f s" % (rep["blender"], rep["version"], rep["generated_utc"], rep["elapsed_s"]))
    L.append("- Targets from: %s%s" % (rep["targets_source"], (" - NOTE: " + rep["targets_note"]) if rep["targets_note"] else ""))
    L.append("")
    L.append("**Items: %d pass, %d fail, %d warn, %d info.**  Overall: **%s**" % (s["pass"], s["fail"], s["warn"], s["info"], s["overall"].upper()))
    L.append("")
    L.append("| Check | Status | pass | fail | warn | info |")
    L.append("|---|---|---|---|---|---|")
    for c in rep["checks"]:
        n = c["counts"]
        L.append("| %s | %s | %d | %d | %d | %d |" % (c["name"], c["status"].upper(), n["pass"], n["fail"], n["warn"], n["info"]))
    L.append("")
    fails = [(c, it) for c in rep["checks"] for it in c["items"] if it["status"] == "fail"]
    L.append("## Failures (%d)" % len(fails))
    L.append("")
    if not fails:
        L.append("None.")
    for c, it in fails:
        L.append("- **[FAIL] %s** (`%s`): %s" % (it["title"], it["id"], md_escape(it["detail"])))
        if it.get("objects"):
            for o in it["objects"][:12]:
                L.append("    - %s" % md_escape(o))
            if len(it["objects"]) > 12:
                L.append("    - ... +%d more (see qa_report.json)" % (len(it["objects"]) - 12))
    L.append("")
    for c in rep["checks"]:
        L.append("## %s - %s" % (c["name"], c["status"].upper()))
        L.append("")
        L.append("| Status | Item | Measured | Expected | Detail |")
        L.append("|---|---|---|---|---|")
        for it in c["items"]:
            meas = it["measured"] if not isinstance(it["measured"], list) else "(%s)" % ", ".join(f(v, 2) for v in it["measured"])
            exp = it["expected"] if not isinstance(it["expected"], list) else "(%s)" % ", ".join(f(v, 2) for v in it["expected"])
            u = (" " + it["unit"]) if it.get("unit") and meas is not None else ""
            L.append("| %s | %s | %s | %s | %s |" % (it["status"].upper(), md_escape(it["title"]), md_escape(f(meas)) + (u if meas is not None else ""),
                                                      md_escape(f(exp)), md_escape(it["detail"])))
        L.append("")
        for it in c["items"]:
            if it.get("objects") and it["status"] in ("fail", "warn", "info"):
                L.append("**%s `%s`** - objects (%d):" % (it["status"].upper(), it["id"], len(it["objects"])))
                for o in it["objects"][:15]:
                    L.append("- %s" % md_escape(o))
                if len(it["objects"]) > 15:
                    L.append("- ... +%d more (see qa_report.json)" % (len(it["objects"]) - 15))
                L.append("")
    return "\n".join(L) + "\n"


def run_check(ctx, cid, name, fn):
    t0 = time.time()
    try:
        items = fn(ctx)
    except Exception:
        items = [item(cid + ".script_error", "check crashed (script error, other checks continue)", "fail",
                      traceback.format_exc()[-1500:], baseline=False)]
    # keep the big per-object health table out of the items list, in the check data
    data = None
    for it in items:
        if it["id"] == "health.totals" and it.get("data"):
            data = {"per_object": it["data"]}
            it["data"] = None
    counts = {k: sum(1 for it in items if it["status"] == k) for k in ("pass", "fail", "warn", "info")}
    res = dict(id=cid, name=name, status=worst(items), counts=counts, seconds=round(time.time() - t0, 2), items=items)
    if data:
        res["data"] = data
    ctx.results.append(res)
    print("[QA] %-14s %-5s pass=%d fail=%d warn=%d info=%d (%.1fs)" % (name, res["status"].upper(), counts["pass"], counts["fail"],
                                                                         counts["warn"], counts["info"], res["seconds"]))
    return res


def main():
    t_start = time.time()
    args = parse_args()
    os.makedirs(args["out"], exist_ok=True)
    load_targets()
    blend = bpy.data.filepath
    blend_info = dict(path=blend, size=os.path.getsize(blend) if blend and os.path.exists(blend) else 0,
                      sha256=file_sha256(blend) if blend and os.path.exists(blend) else "")
    print("[QA] model: %s (%s)" % (blend, blend_info["sha256"][:12]))
    ctx = None
    try:
        ctx = Ctx(args)
    except Exception:
        print(traceback.format_exc())
    checks = [("contract", "1 Contract", check_contract), ("targets", "2 Targets", check_targets),
              ("health", "3 Mesh health", check_health), ("interference", "4 Interference", check_interference),
              ("entry", "5 Entry opening", check_entry), ("export", "6 Export round-trip", check_export),
              ("regression", "7 Regression", check_regression)]
    if ctx is None:
        class Dead:
            results = []
        d = Dead()
        d.results.append(dict(id="setup", name="Setup", status="fail", counts=dict(**{"pass": 0, "fail": 1, "warn": 0, "info": 0}), seconds=0,
                              items=[item("setup.context", "build scene context", "fail", "scene context failed to build; see Blender console")]))
        results = d.results
    else:
        for cid, name, fn in checks:
            run_check(ctx, cid, name, fn)
        results = ctx.results
    tot = {k: sum(r["counts"][k] for r in results) for k in ("pass", "fail", "warn", "info")}
    tot["overall"] = "fail" if tot["fail"] else ("warn" if tot["warn"] else "pass")
    rep = dict(tool="qa_check", version=VERSION, blender=bpy.app.version_string if bpy.app else "",
               generated_utc=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
               elapsed_s=round(time.time() - t_start, 1), blend=blend_info, targets_source=TARGETS_SOURCE, targets_note=TARGETS_NOTE,
               args={k: v for k, v in args.items()}, tolerances=TOL, summary=tot, checks=results)
    with open(os.path.join(args["out"], "qa_report.json"), "w", encoding="utf-8") as fh:
        json.dump(rep, fh, indent=1, default=json_default)
    with open(os.path.join(args["out"], "QA_SUMMARY.md"), "w", encoding="utf-8") as fh:
        fh.write(build_markdown(rep))
    print("[QA] DONE overall=%s pass=%d fail=%d warn=%d info=%d -> %s" % (tot["overall"], tot["pass"], tot["fail"], tot["warn"], tot["info"], args["out"]))
    if args["strict"] and tot["fail"]:
        sys.exit(1)


if __name__ == "__main__" or True:
    main()
