"""CLAUDE1 · Terrace T01 authoring checkpoint (proposed design candidate, not engine-verified).

    <bpy python> docs/crown-key-production/R02/claude-tooling/terrace/author_t01.py --out OUTDIR
    python docs/crown-key-production/R02/claude-tooling/terrace/author_t01.py --check PACKAGE_DIR   # no Blender needed

Stage 1  runs the merged PR #51 pipeline unchanged on the Terrace candidate contract
         (tools/contracts/blockout.py): contract blockout .blend, blockout .glb (collision),
         annotations .glb, saved cameras, neutral renders, ray / floor-support / round-trip checks.
Stage 2  authors the lobby, studio and lounge: applies the shared material library to the
         room surfaces and replaces the 19 furniture proxy boxes with named prop variants
         built from the shared prop kit. Nothing in the contract is changed: every prop is
         built inside its proxy's footprint and height, and the checks below prove it.

Inputs are read, never edited: terrace/BUILDING_DIMENSIONS.json, MATERIALS_AND_PROPS.json,
ROUTES.json, CAMERAS.json and ../materials/*.json. Everything the contract does not state
(prop facing, prop detailing) is recorded as an assumption in the manifest.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import shutil
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[4]
RUN = ROOT / "docs/crown-key-production/R02/production-run/R01"
TERRACE = RUN / "terrace"
CONTRACT = TERRACE / "BUILDING_DIMENSIONS.json"
SCRIPT_VERSION = "T01-A1"
EPS = 1e-4


def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


# ---------------------------------------------------------------------------
# Prop part tables. Local frame: origin at the footprint centre on the floor, +Y = front
# of the prop, width along X, depth along Y, height Z. Each part is
# (name, slot, x0, y0, z0, x1, y1, z1) in metres, derived from the variant's (w, d, h).
# Slots index the kit specification's material_slots; a slot name beyond the kit's is a
# declared T01 variant addition (foliage) and is recorded as such.
# ---------------------------------------------------------------------------

def _b(name, slot, x0, y0, z0, x1, y1, z1):
    return (name, slot, x0, y0, z0, x1, y1, z1)


def parts_for(kit, w, d, h):
    hw, hd = w / 2, d / 2
    P = []
    hulls = []
    if kit == "CK_PROP_P002":  # reception desk: stone shell, bronze kick, timber top, bronze front strip
        P += [_b("kick", 1, -hw + .04, -hd + .04, 0, hw - .04, hd - .04, .06),
              _b("shell", 0, -hw, -hd, .06, hw, hd - .02, h - .05),
              _b("front_strip", 1, -hw, hd - .02, .06, hw, hd, h - .05),
              _b("top", 2, -hw, -hd, h - .05, hw, hd, h)]
        hulls = [("shell_box", (-hw, -hd, 0, hw, hd, h - .05)), ("top_box", (-hw, -hd, h - .05, hw, hd, h))]
    elif kit == "CK_PROP_P007":  # gallery bench
        leg = .12
        P += [_b("leg_a", 1, -hw + .3, -hd + .05, 0, -hw + .3 + leg, hd - .05, h - .07),
              _b("leg_b", 1, hw - .3 - leg, -hd + .05, 0, hw - .3, hd - .05, h - .07),
              _b("seat", 0, -hw, -hd, h - .07, hw, hd, h)]
        hulls = [("seat_box", (-hw, -hd, h - .07, hw, hd, h)), ("base_boxes", (-hw + .3, -hd + .05, 0, hw - .3, hd - .05, h - .07))]
    elif kit == "CK_PROP_P009":  # linear planter: ivory vessel, soil, foliage (T01 variant slot)
        vh = round(h * .6, 4)
        P += [_b("vessel", 0, -hw, -hd, 0, hw, hd, vh),
              _b("soil", 1, -hw + .06, -hd + .06, vh, hw - .06, hd - .06, vh + .05)]
        n = 3
        for i in range(n):
            cx = -hw + (i + .5) * w / n
            P.append(("foliage_%d" % i, 2, "ELLIPSOID", cx, 0, vh + .05 + (h - vh - .05) / 2, w / n * .46, (d - .16) * .5, (h - vh - .05) / 2))
        hulls = [("box", (-hw, -hd, 0, hw, hd, h))]
    elif kit == "CK_PROP_P013":  # bed: head at the back (-Y), linen mattress, timber frame and headboard
        P += [_b("frame", 1, -hw, -hd, .08, hw, hd, .3),
              _b("headboard", 1, -hw, -hd, .3, hw, -hd + .08, h),
              _b("mattress", 0, -hw + .04, -hd + .08, .3, hw - .04, hd - .04, .5),
              _b("pillow_a", 0, -hw + .12, -hd + .12, .5, -.04, -hd + .5, .57),
              _b("pillow_b", 0, .04, -hd + .12, .5, hw - .12, -hd + .5, .57),
              _b("foot_a", 1, -hw, hd - .1, 0, -hw + .1, hd, .08), _b("foot_b", 1, hw - .1, hd - .1, 0, hw, hd, .08),
              _b("head_a", 1, -hw, -hd, 0, -hw + .1, -hd + .1, .08), _b("head_b", 1, hw - .1, -hd, 0, hw, -hd + .1, .08)]
        hulls = [("frame_box", (-hw, -hd, 0, hw, hd, .3)), ("mattress_box", (-hw, -hd, .3, hw, hd, h))]
    elif kit == "CK_PROP_P017":  # wardrobe: plinth, carcass, two doors, handles
        P += [_b("plinth", 1, -hw + .03, -hd + .03, 0, hw - .03, hd - .03, .06),
              _b("carcass", 0, -hw, -hd, .06, hw, hd - .02, h),
              _b("door_a", 0, -hw, hd - .02, .06, -.005, hd, h), _b("door_b", 0, .005, hd - .02, .06, hw, hd, h),
              _b("handle_a", 1, -.09, hd - .02, 1.0, -.07, hd, 1.4), _b("handle_b", 1, .07, hd - .02, 1.0, .09, hd, 1.4)]
        hulls = [("box", (-hw, -hd, 0, hw, hd, h))]
    elif kit == "CK_PROP_P003":  # lounge sofa
        arm = .16
        P += [_b("leg_a", 2, -hw + .08, -hd + .08, 0, -hw + .16, -hd + .16, .12), _b("leg_b", 2, hw - .16, -hd + .08, 0, hw - .08, -hd + .16, .12),
              _b("leg_c", 2, -hw + .08, hd - .16, 0, -hw + .16, hd - .08, .12), _b("leg_d", 2, hw - .16, hd - .16, 0, hw - .08, hd - .08, .12),
              _b("frame", 1, -hw, -hd, .12, hw, hd, .26),
              _b("arm_a", 1, -hw, -hd, .26, -hw + arm, hd, min(.62, h - .1)), _b("arm_b", 1, hw - arm, -hd, .26, hw, hd, min(.62, h - .1)),
              _b("seat", 0, -hw + arm, -hd + .22, .26, hw - arm, hd, .46),
              _b("back", 0, -hw + arm, -hd, .26, hw - arm, -hd + .22, h)]
        hulls = [("seat_box", (-hw, -hd, 0, hw, hd, .46)), ("back_box", (-hw, -hd, .46, hw, -hd + .22, h))]
    elif kit == "CK_PROP_P005":  # coffee table: stone top on a bronze plinth
        P += [_b("base", 1, -hw + .12, -hd + .1, 0, hw - .12, hd - .1, h - .05), _b("top", 0, -hw, -hd, h - .05, hw, hd, h)]
        hulls = [("tabletop_box", (-hw, -hd, h - .05, hw, hd, h)), ("base_convex", (-hw + .12, -hd + .1, 0, hw - .12, hd - .1, h - .05))]
    elif kit == "CK_PROP_P014":  # kitchenette run: dark plinth, timber base units, stone counter, sink, hob
        P += [_b("plinth", 2, -hw + .03, -hd + .03, 0, hw - .03, hd - .03, .08),
              _b("base_units", 0, -hw, -hd, .08, hw, hd, .84),
              _b("counter", 1, -hw, -hd, .84, hw, hd, h - .02),
              _b("sink", 3, -hw + .6, -hd + .12, h - .02, -hw + 1.2, hd - .12, h),
              _b("hob", 2, hw - 1.3, -hd + .12, h - .02, hw - .6, hd - .12, h)]
        hulls = [("base_boxes", (-hw, -hd, 0, hw, hd, .84)), ("upper_boxes", (-hw, -hd, .84, hw, hd, h))]
    elif kit == "CK_PROP_P015":  # dining table / island: timber top on four bronze legs
        leg = .07
        P += [_b("leg_%d" % i, 1, sx * (hw - .05) - (leg if sx > 0 else 0), sy * (hd - .05) - (leg if sy > 0 else 0), 0,
                 sx * (hw - .05) + (0 if sx > 0 else leg), sy * (hd - .05) + (0 if sy > 0 else leg), h - .06)
              for i, (sx, sy) in enumerate([(-1, -1), (1, -1), (-1, 1), (1, 1)])]
        P.append(_b("top", 0, -hw, -hd, h - .06, hw, hd, h))
        hulls = [("tabletop_box", (-hw, -hd, h - .06, hw, hd, h)), ("leg_boxes", (-hw + .05, -hd + .05, 0, hw - .05, hd - .05, h - .06))]
    elif kit == "CK_PROP_P022":  # toilet: tank at the back, bowl at the front
        P += [_b("tank", 0, -hw + .08, -hd, 0, hw - .08, -hd + .2, h - .02),
              _b("bowl", 0, -hw + .06, -hd + .2, 0, hw - .06, hd, .4),
              _b("flush", 1, -.04, -hd + .08, h - .02, .04, -hd + .12, h)]
        hulls = [("hull_tank", (-hw + .08, -hd, 0, hw - .08, -hd + .2, h)), ("hull_bowl", (-hw + .06, -hd + .2, 0, hw - .06, hd, .4))]
    elif kit == "CK_PROP_P021":  # vanity: timber cabinet, stone top, sand basin, bronze tap
        P += [_b("cabinet", 0, -hw, -hd, 0, hw, hd, h - .1),
              _b("top", 1, -hw, -hd, h - .1, hw, hd, h - .04),
              _b("basin", 2, -hw + .12, -hd + .06, h - .04, hw - .12, hd - .04, h),
              _b("tap", 3, -.02, -hd + .02, h - .04, .02, -hd + .06, h)]
        hulls = [("cabinet_box", (-hw, -hd, 0, hw, hd, h))]
    elif kit == "CK_PROP_P023":  # shower tray only: the contract proxy is a 6 cm tray, no enclosure bounds
        P += [_b("tray", 2, -hw, -hd, 0, hw, hd, h - .004), _b("drain", 1, -.06, -.06, h - .004, .06, .06, h)]
        hulls = [("frame_boxes", (-hw, -hd, 0, hw, hd, h))]
    else:  # pragma: no cover
        raise ValueError(f"no part table for {kit}")
    return P, hulls


# material slot names per kit prop, beyond the kit spec where flagged as a variant addition
EXTRA_SLOTS = {"CK_PROP_P009": ["CK_MAT_008_FOLIAGE_GREEN"], "CK_PROP_P003": [], }
SLOT_FALLBACK = {"CK_PROP_P014": 3}


def room_of(pt, rooms):
    for rid, (x0, y0, x1, y1) in rooms.items():
        if x0 <= pt[0] <= x1 and y0 <= pt[1] <= y1:
            return rid
    return None


def author(out: Path):
    sys.path.insert(0, str(ROOT / "tools/contracts"))
    import bpy
    import bmesh
    import blockout
    import contract as C
    import views
    from mathutils import Euler, Matrix, Vector

    out.mkdir(parents=True, exist_ok=True)
    (out / "blockout").mkdir(exist_ok=True)
    (out / "authored/renders").mkdir(parents=True, exist_ok=True)

    # ---------------- stage 1: the unchanged PR #51 pipeline ----------------
    code = blockout.main([str(CONTRACT), "--out", str(out / "blockout"), "--views"])
    bman = json.loads(next((out / "blockout").glob("*_BLOCKOUT_MANIFEST.json")).read_text())
    if code != 0 or bman["verification"] != "PASS":
        sys.exit(f"STOP: stage 1 blockout did not pass (exit {code}, {bman['verification']})")
    data, prov = C.load(CONTRACT)
    rep = C.analyse(data)
    st = C.stamp(data, prov)
    prefix = C.output_prefix(data)
    gate = C.issue_gate(data, prov, C.rel_path(CONTRACT))
    if gate["issuable"]:
        sys.exit("STOP: the issue gate accepted a draft candidate outside production/; this must not happen")

    # ---------------- stage 2: materials ----------------
    mats_src = {m["id"]: m for m in json.loads((RUN / "materials/material_library.json").read_text())["materials"]}
    mp = json.loads((TERRACE / "MATERIALS_AND_PROPS.json").read_text())
    kit = {p["id"]: p for p in json.loads((RUN / "materials/prop_bill.json").read_text())["props"]}
    # blockout.main() ends with a glTF round trip that resets Blender; reopen the .blend it saved first
    bpy.ops.wm.open_mainfile(filepath=str(out / "blockout" / f"{prefix}_BLOCKOUT.blend"))
    scene = bpy.context.scene
    made = {}

    def kit_material(mid):
        if mid in made:
            return made[mid]
        s = mats_src[mid]
        m = bpy.data.materials.new(mid)
        m.use_nodes = True
        b = m.node_tree.nodes["Principled BSDF"]
        lin = s["base_color"]["linear_rgb"]
        b.inputs["Base Color"].default_value = (lin[0], lin[1], lin[2], 1.0)
        b.inputs["Roughness"].default_value = s["roughness"]
        b.inputs["Metallic"].default_value = s["metallic"]
        b.inputs["IOR"].default_value = s["ior"]
        b.inputs["Transmission Weight"].default_value = s["transmission_weight"]
        m.diffuse_color = (lin[0], lin[1], lin[2], 1.0)
        m.roughness = s["roughness"]
        m.metallic = s["metallic"]
        m["lsc_material_id"] = mid
        m["lsc_status"] = s["status"]
        m["lsc_baked_maps"] = "none: procedural bump is not baked or exported"
        made[mid] = m
        return m

    def set_all(ob, mid):
        ob.data.materials.clear()
        ob.data.materials.append(kit_material(mid))
        ob["lsc_material"] = mid

    objs = {o.name: o for o in bpy.data.objects}
    b = mp["bindings"]
    applied, unapplied = [], []

    def apply(objname, mid, why):
        if objname in objs:
            set_all(objs[objname], mid)
            applied.append({"object": objname, "material": mid, "binding": why})
        else:
            unapplied.append({"object": objname, "why": "object not found in blockout"})

    for room in ("LOBBY", "LOUNGE", "STUDIO"):
        r = b[room]
        apply(f"WALLS_{room}", r["walls"], f"{room}.walls")
        apply(f"SLAB_{room}_L00", r["floor"], f"{room}.floor")
    apply("ROOF_LOUNGE", b["LOUNGE"]["ceiling"], "LOUNGE.ceiling")
    apply("MASS_STUDIO_CEILING", b["STUDIO"]["ceiling"], "STUDIO.ceiling")
    for n in ("BATH_WALL_S", "BATH_WALL_N", "BATH_JAMB_SW", "BATH_JAMB_NW", "BATH_DOOR_HEAD"):
        apply(f"MASS_{n}", b["STUDIO_BATH"]["walls_and_floor"], "STUDIO_BATH.walls_and_floor")
    for i in range(1, 7):
        apply(f"MASS_TERRACE_TIER_{i:02d}", b["TERRACE_TIERS"]["structure"], "TERRACE_TIERS.structure")
    not_applied_bindings = ["LOBBY.ceiling (not bound)", "STUDIO_BATH floor (no separate bath floor object; studio slab keeps the studio floor)",
                            "TOWER_CLOSED facade_intent glass / bands (closed massing, intent only)", "TERRACE_TIERS.soffits (no soffit objects)"]

    # ---------------- stage 2: props replace the proxy boxes ----------------
    d = rep["derived"]
    masses = {m["id"]: m for m in d["masses"]}
    rooms = {}
    for rid in ("LOBBY", "LOUNGE", "STUDIO"):
        xs = [p[0] for p in masses[rid]["footprint"]]
        ys = [p[1] for p in masses[rid]["footprint"]]
        rooms[rid] = (min(xs), min(ys), max(xs), max(ys))
    centre = {rid: ((a + c) / 2, (bb + dd) / 2) for rid, (a, bb, c, dd) in rooms.items()}
    cb = bpy.data.collections["BLOCKOUT"]
    props_c = bpy.data.collections.new("PROPS")
    hull_c = bpy.data.collections.new("PROP_COLLISION")
    scene.collection.children.link(props_c)
    scene.collection.children.link(hull_c)
    contract_masses = {m["id"]: m for m in data["geometry"]["masses"]}
    bath_ids = [p["proxy_id"] for p in mp["props"] if p["proxy_id"].startswith("BATH_")]

    def bounds(m):
        xs = [p[0] for p in m["footprint"]]
        ys = [p[1] for p in m["footprint"]]
        return min(xs), min(ys), max(xs), max(ys)

    bath_centre = (sum((bounds(masses[i])[0] + bounds(masses[i])[2]) / 2 for i in bath_ids) / len(bath_ids),
                   sum((bounds(masses[i])[1] + bounds(masses[i])[3]) / 2 for i in bath_ids) / len(bath_ids))
    records, assumptions = [], []
    proxy_objs = []
    for p in mp["props"]:
        pid, kid = p["proxy_id"], p["kit_reference"]
        m = masses[pid]
        x0, y0, x1, y1 = bounds(m)
        px, py, h = x1 - x0, y1 - y0, m["z1"] - m["z0"]
        cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
        spec = kit[kid]["dimensions_m"]
        swap = (spec["width_x"] >= spec["depth_y"]) != (px >= py)
        lw, ld = (py, px) if swap else (px, py)
        host = room_of((cx, cy), rooms)
        if pid.startswith("BATH_"):
            target, tname = bath_centre, "bath centre"
        elif host:
            target, tname = centre[host], f"{host} centre"
        else:
            target, tname = centre["LOUNGE"], "LOUNGE centre (outdoor terrace planter)"
        tx, ty = target[0] - cx, target[1] - cy
        cand = (90, 270) if swap else (0, 180)
        fronts = {0: (0, 1), 180: (0, -1), 90: (-1, 0), 270: (1, 0)}
        theta = max(cand, key=lambda t: fronts[t][0] * tx + fronts[t][1] * ty)
        parts, hulls = parts_for(kid, lw, ld, h)
        # mesh
        bm = bmesh.new()
        slots = []
        for part in parts:
            if part[2] == "ELLIPSOID":
                ex, ey, ez, rx, ry, rz = part[3:9]
                res = bmesh.ops.create_uvsphere(bm, u_segments=8, v_segments=6, radius=1.0)
                ext = [max(abs(v.co[i]) for v in res["verts"]) for i in range(3)]
                for v in res["verts"]:  # normalise to an exact unit ellipsoid so its bounds are the stated radii
                    v.co = (ex + v.co.x / ext[0] * rx, ey + v.co.y / ext[1] * ry, ez + v.co.z / ext[2] * rz)
                for f in {f for v in res["verts"] for f in v.link_faces}:
                    f.material_index = slot
                continue
            nm, slot, a0, b0, c0, a1, b1, c1 = part
            res = bmesh.ops.create_cube(bm, size=1.0)
            for v in res["verts"]:
                v.co = (a0 if v.co.x < 0 else a1, b0 if v.co.y < 0 else b1, c0 if v.co.z < 0 else c1)
            for f in {f for v in res["verts"] for f in v.link_faces}:
                f.material_index = slot
        bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
        variant = f"{kid}__T01_{int(round(lw*1000))}x{int(round(ld*1000))}x{int(round(h*1000))}"
        me = bpy.data.meshes.new("PROP_" + pid)
        bm.to_mesh(me)
        bm.free()
        ob = bpy.data.objects.new("PROP_" + pid, me)
        props_c.objects.link(ob)
        slot_ids = [s["default_material"] for s in kit[kid]["material_slots"]] + EXTRA_SLOTS.get(kid, [])
        for sid in slot_ids:
            me.materials.append(kit_material(sid))
        ob.location = (cx, cy, m["z0"])
        ob.rotation_euler = Euler((0, 0, math.radians(theta)))
        for k, v in {"lsc_id": pid, "lsc_type": "prop", "lsc_asset_id": st["asset_id"], "lsc_contract_revision": st["contract_revision"],
                     "lsc_contract_sha256": st["contract_sha256"], "lsc_kit_reference": kid, "lsc_variant": variant,
                     "lsc_source_proxy": f"MASS_{pid}", "lsc_pivot": "floor_center", "lsc_collision": "see PROP_COLLISION hulls (simple_compound_convex, untested)",
                     "lsc_status": "authored_prop_variant_not_finished_asset", "lsc_facing_toward": tname}.items():
            ob[k] = v
        pr = objs.get(f"MASS_{pid}")
        if pr:
            proxy_objs.append(pr)
        for i, (hn, (a0, b0, c0, a1, b1, c1)) in enumerate(hulls, 1):
            hm = bpy.data.meshes.new(f"UCX_{pid}_{i:02d}")
            hb = bmesh.new()
            res = bmesh.ops.create_cube(hb, size=1.0)
            for v in res["verts"]:
                v.co = (a0 if v.co.x < 0 else a1, b0 if v.co.y < 0 else b1, c0 if v.co.z < 0 else c1)
            hb.to_mesh(hm)
            hb.free()
            ho = bpy.data.objects.new(f"UCX_{pid}_{i:02d}", hm)
            hull_c.objects.link(ho)
            ho.parent = ob
            ho["lsc_role"] = "collision_hull"
            ho["lsc_hull_part"] = hn
            ho["lsc_collision_for"] = ob.name
        records.append({"proxy_id": pid, "kit_reference": kid, "kit_name": kit[kid]["name"], "variant": variant,
                        "kit_dims_wxdxh_m": [spec["width_x"], spec["depth_y"], spec["height_z"]], "authored_dims_wxdxh_m": [round(lw, 4), round(ld, 4), round(h, 4)],
                        "differs_from_kit": [round(lw - spec["width_x"], 4), round(ld - spec["depth_y"], 4), round(h - spec["height_z"], 4)],
                        "rotated_90_to_fit_footprint": swap, "rotation_z_deg": theta, "front_faces": tname, "host_room": host,
                        "centre_m": [round(cx, 4), round(cy, 4)], "footprint_bounds_m": [x0, y0, x1, y1], "z_top_m": m["z1"],
                        "kit_slots": [s["default_material"] for s in kit[kid]["material_slots"]], "variant_added_slots": EXTRA_SLOTS.get(kid, []),
                        "collision_hulls": [h_[0] for h_ in hulls]})
    assumptions += [
        "Prop facing is not in the contract. Each prop's front (+Y in the kit) faces the centre of its host room; bath fixtures face the bath centre; outdoor planters are symmetric. Codex or the prop owner should confirm or correct each facing.",
        "Pivot is floor_center for every prop. The kit lists wall_back_bottom_center for the wardrobe, kitchenette and vanity; those objects sit at the same place, so only the pivot convention differs.",
        "Where an authored footprint differs from the kit specification the prop is a named T01 variant at the authored size; nothing is scaled. Differences are listed per prop in the manifest.",
        "Detailing (door gaps, handles, cushions, basin, foliage blobs) is the author's simple blocked form inside the proxy bounds, not a finished mesh.",
        "Room-surface materials are one slot per wall object, so the inner and outer faces of a hollow room share the bound wall material.",
        "Foliage uses CK_MAT_008_FOLIAGE_GREEN as a declared variant slot; the kit's planter lists only ivory vessel and soil.",
    ]

    # ---------------- stage 2 checks (against the candidate contract) ----------------
    bpy.context.view_layer.update()
    checks = {"prop_inside_proxy": [], "prop_footprint_coverage": [], "route_clearance": []}
    ok_all = True
    prop_obs = [o for o in props_c.objects]
    for ob_, rec in zip(prop_obs, records):
        mn, mx = blockout.world_bbox([ob_])
        x0, y0, x1, y1 = rec["footprint_bounds_m"]
        inside = mn[0] >= x0 - EPS and mn[1] >= y0 - EPS and mx[0] <= x1 + EPS and mx[1] <= y1 + EPS and mn[2] >= -EPS and mx[2] <= rec["z_top_m"] + EPS
        cover = (mx[0] - mn[0]) * (mx[1] - mn[1]) / ((x1 - x0) * (y1 - y0))  # informational: a prop smaller than its proxy is allowed
        checks["prop_inside_proxy"].append({"id": rec["proxy_id"], "pass": inside, "bbox_min": [round(v, 4) for v in mn], "bbox_max": [round(v, 4) for v in mx]})
        checks["prop_footprint_coverage"].append({"id": rec["proxy_id"], "bbox_xy_area_ratio_of_proxy": round(cover, 4), "bbox_top_m": round(mx[2], 4), "proxy_top_m": rec["z_top_m"], "pass": True})
        ok_all &= inside

    # route clearance of the actual part boxes against the same body model Codex used
    routes = json.loads((TERRACE / "ROUTES.json").read_text())
    rad = routes["clearance_test"]["body_radius_m"] + routes["clearance_test"]["extra_radial_margin_m"]

    def rect_dist(px_, py_, r):
        dx = max(r[0] - px_, 0, px_ - r[2])
        dy = max(r[1] - py_, 0, py_ - r[3])
        return math.hypot(dx, dy)

    def part_rects(ob_):
        rects = []
        mw = ob_.matrix_world
        for hlb in ob_.children:
            pts = [hlb.matrix_world @ Vector(c) for c in hlb.bound_box]
            rects.append((min(p.x for p in pts), min(p.y for p in pts), max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
        return rects

    prop_rects = {r["proxy_id"]: part_rects(o) for o, r in zip(prop_obs, records)}
    for route in routes["routes"]:
        pts = [(q[0], q[1]) for q in route["points_m"]]
        worst = {"proxy": 1e9, "prop": 1e9}
        for (ax, ay), (bx, by) in zip(pts, pts[1:]):
            n = max(int(math.hypot(bx - ax, by - ay) / 0.05), 1)
            for i in range(n + 1):
                q = (ax + (bx - ax) * i / n, ay + (by - ay) * i / n)
                for r_ in records:
                    x0, y0, x1, y1 = r_["footprint_bounds_m"]
                    worst["proxy"] = min(worst["proxy"], rect_dist(q[0], q[1], (x0, y0, x1, y1)) - rad)
                    for rc in prop_rects[r_["proxy_id"]]:
                        worst["prop"] = min(worst["prop"], rect_dist(q[0], q[1], rc[:4]) - rad)
        ok = worst["prop"] >= worst["proxy"] - 1e-9
        checks["route_clearance"].append({"route": route["id"], "body_radius_plus_margin_m": rad, "min_clearance_to_proxies_m": round(worst["proxy"], 4),
                                          "min_clearance_to_props_m": round(worst["prop"], 4), "pass": ok})
        ok_all &= ok

    # ---------------- authored scene: drop the proxies, re-run the pipeline checks ----------------
    for pr in proxy_objs:
        bpy.data.objects.remove(pr, do_unlink=True)
    bpy.context.view_layer.update()
    built = [o for o in cb.objects]
    rays = blockout.ray_tests(rep, built + list(props_c.objects))
    support = blockout.floor_support_tests(rep, built + list(props_c.objects))
    dups = blockout.duplicate_floor_faces(built)
    ok_all &= all(r["pass"] for r in rays) and all(r["pass"] for r in support) and not dups

    # ---------------- renders, .blend, exports ----------------
    a_dir = out / "authored"
    glb_b = a_dir / f"{prefix}_AUTHORED_BLOCKOUT.glb"
    glb_p = a_dir / f"{prefix}_PROPS.glb"
    blend = a_dir / f"{prefix}_AUTHORED.blend"
    for o in hull_c.objects:
        o.display_type = "WIRE"
    mn_b, mx_b = blockout.world_bbox(built)
    mn_p, mx_p = blockout.world_bbox(list(props_c.objects) + list(hull_c.objects))
    cams_req = json.loads((TERRACE / "CAMERAS.json").read_text())["views"]
    ann = bpy.data.collections.get("ANNOTATIONS")
    if ann:
        ann.hide_render = True
    hull_c.hide_render = True
    view_records = []
    for v in cams_req:
        scene.render.resolution_x, scene.render.resolution_y = v["resolution_px"]
        cam = views.add_camera("CAM_T01_" + v["id"], tuple(v["location_m"]), tuple(v["target_m"]), None, lens=v["lens_mm"])
        scene.camera = cam
        img = a_dir / "renders" / f"{prefix}_AUTHORED_{v['id']}.png"
        scene.render.filepath = str(img)
        bpy.ops.render.render(write_still=True)
        view_records.append({"id": v["id"], "file": f"authored/renders/{img.name}", "sha256": sha(img), "location_m": v["location_m"], "target_m": v["target_m"],
                             "lens_mm": v["lens_mm"], "resolution_px": v["resolution_px"], "engine": scene.render.engine,
                             "status": "authored_geometry_preview_not_appearance_not_engine_evidence"})
    if ann:
        ann.hide_render = False
    blockout.export(cb, glb_b)
    pc = bpy.data.collections.new("PROPS_EXPORT")
    scene.collection.children.link(pc)
    for o in list(props_c.objects) + list(hull_c.objects):
        pc.objects.link(o)
    blockout.export(pc, glb_p)
    for o in list(pc.objects):
        pc.objects.unlink(o)
    bpy.data.collections.remove(pc)
    bpy.ops.wm.save_as_mainfile(filepath=str(blend), compress=False)
    rt_b = blockout.roundtrip(glb_b, mn_b, mx_b, {})
    rt_p = blockout.roundtrip(glb_p, mn_p, mx_p, {})
    ok_all &= rt_b["pass"] and rt_p["pass"]
    import platform
    result = {
        "script": f"author_t01.py {SCRIPT_VERSION}",
        "stamp": st,
        "contract_file_sha256": sha(CONTRACT),
        "issue_gate": {"issuable": False, "first_problems": gate["problems"][:5]},
        "tools": {"blender": bman["blender"], "gltf_exporter": bman["export"]["exporter"], "python": sys.version.split()[0], "platform": platform.platform()},
        "stage1_blockout": {"verification": bman["verification"], "extent_m": bman["extent_m"], "extent_expected_in_unreal_cm": bman["extent_expected_in_unreal_cm"],
                            "ray_tests": f"{sum(r['pass'] for r in bman['ray_tests'])}/{len(bman['ray_tests'])}",
                            "floor_support": f"{sum(r['pass'] for r in bman['floor_support'])}/{len(bman['floor_support'])}",
                            "duplicate_floor_faces": len(bman["duplicate_floor_faces"]), "roundtrip": bman["gltf_roundtrip"]["pass"],
                            "objects": len(bman["objects"]), "hashes": bman["hashes"]},
        "stage2_authored": {"props": len(records), "proxies_removed": len(proxy_objs), "materials_created": sorted(made),
                            "ray_tests": f"{sum(r['pass'] for r in rays)}/{len(rays)}", "floor_support": f"{sum(r['pass'] for r in support)}/{len(support)}",
                            "duplicate_floor_faces": len(dups),
                            "roundtrip_blockout": {"pass": rt_b["pass"], "bbox_min": rt_b["bbox_min"], "bbox_max": rt_b["bbox_max"]},
                            "roundtrip_props": {"pass": rt_p["pass"], "bbox_min": rt_p["bbox_min"], "bbox_max": rt_p["bbox_max"]}},
        "materials_applied": applied, "materials_not_applied": not_applied_bindings + unapplied,
        "props": records, "checks": checks, "assumptions": assumptions, "renders": view_records,
        "verification": "PASS" if ok_all else "FAIL",
    }
    (a_dir / f"{prefix}_AUTHORED_MANIFEST.json").write_text(json.dumps(result, indent=2, sort_keys=True, default=str) + "\n")
    print(f"authored: props {len(records)} · inside proxies {sum(c['pass'] for c in checks['prop_inside_proxy'])}/{len(records)} · "
          f"routes {sum(c['pass'] for c in checks['route_clearance'])}/{len(checks['route_clearance'])} · rays {result['stage2_authored']['ray_tests']} · "
          f"floor support {result['stage2_authored']['floor_support']} · round-trip {'PASS' if rt_b['pass'] and rt_p['pass'] else 'FAIL'} · {result['verification']}")
    return 0 if ok_all else 1


INPUTS = [
    "docs/crown-key-production/R02/production-run/R01/terrace/BUILDING_DIMENSIONS.json",
    "docs/crown-key-production/R02/production-run/R01/terrace/MATERIALS_AND_PROPS.json",
    "docs/crown-key-production/R02/production-run/R01/terrace/ROUTES.json",
    "docs/crown-key-production/R02/production-run/R01/terrace/CAMERAS.json",
    "docs/crown-key-production/R02/production-run/R01/materials/material_library.json",
    "docs/crown-key-production/R02/production-run/R01/materials/prop_bill.json",
    "tools/contracts/blockout.py", "tools/contracts/contract.py", "tools/contracts/views.py",
]


def seal(pkg: Path):
    """Write MANIFEST.json for a finished package folder (plain Python, no Blender). Re-run after adding REPORT.md etc."""
    am = next(pkg.glob("authored/*_AUTHORED_MANIFEST.json"))
    r = json.loads(am.read_text())
    files = {}
    for q in sorted(pkg.rglob("*")):
        if q.is_file() and q.name != "MANIFEST.json":
            rel = q.relative_to(pkg).as_posix()
            files[rel] = {"sha256": sha(q), "bytes": q.stat().st_size, "byte_reproducible": not rel.endswith(".blend")}
    man = {
        "package": "CLAUDE1 Terrace T01 authoring checkpoint", "status": "PROPOSED_DESIGN_CANDIDATE_BLENDER_EXECUTED_ENGINE_NOT_TESTED",
        "script": r["script"], "asset_id": r["stamp"]["asset_id"], "contract_revision": r["stamp"]["contract_revision"],
        "contract_file_sha256": r["contract_file_sha256"], "canonical_contract_hash": r["stamp"]["contract_sha256"],
        "tools": r["tools"], "verification": r["verification"],
        "script_file": {"path": "docs/crown-key-production/R02/claude-tooling/terrace/author_t01.py", "sha256": sha(HERE / "author_t01.py")},
        "inputs_read_only": {rel: sha(ROOT / rel) for rel in INPUTS},
        "engine_status": {"unreal_import": "not_tested", "collision": "not_tested", "traversal": "not_tested", "navmesh": "not_tested"},
        "reproduce": "see REPRODUCE.md", "files": files,
    }
    (pkg / "MANIFEST.json").write_text(json.dumps(man, indent=2, sort_keys=True) + "\n")
    print(f"sealed: {len(files)} files, MANIFEST.json sha256 {sha(pkg / 'MANIFEST.json')}")
    return 0


def check(pkg: Path):
    man = json.loads((pkg / "MANIFEST.json").read_text())
    errs = []
    present = {q.relative_to(pkg).as_posix() for q in pkg.rglob("*") if q.is_file() and q.name != "MANIFEST.json"}
    listed = set(man["files"])
    if present != listed:
        errs.append(f"file set differs (extra {sorted(present - listed)[:3]}, missing {sorted(listed - present)[:3]})")
    for rel, rec in man["files"].items():
        if (pkg / rel).is_file() and sha(pkg / rel) != rec["sha256"]:
            errs.append(f"{rel}: SHA-256 differs from MANIFEST.json")
    if errs:
        print("PACKAGE CHECK FAILED:\n  " + "\n  ".join(errs))
        return 1
    print(f"PASS: {len(listed)} files match MANIFEST.json")
    return 0


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--out")
    ap.add_argument("--check")
    ap.add_argument("--seal")
    a = ap.parse_args()
    if a.seal:
        sys.exit(seal(Path(a.seal)))
    if a.check:
        sys.exit(check(Path(a.check)))
    if not a.out:
        ap.error("--out or --check required")
    out = Path(a.out).resolve()
    base = (HERE / "T01").resolve()
    if out.parent != base.parent or not out.name.startswith("T01") or out.is_symlink():
        sys.exit(f"REFUSED: --out must be a T01* folder directly inside {HERE.as_posix()} (got {out})")
    if out.exists():
        shutil.rmtree(out)
    sys.exit(author(out))


if __name__ == "__main__":
    main()
