#!/usr/bin/env python3
"""Review-only SVG/PDF/OBJ pipeline reusing the merged schema-v2 derivation.

No input contract or original tool is modified. Blender/Unreal checks are NOT
substituted by this fallback. Run from any directory; see README.md.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
import math
import os
from pathlib import Path
import sys
import textwrap
from xml.sax.saxutils import escape

HERE = Path(__file__).resolve().parent
CACHE = HERE / "source-cache/tools/contracts"
REPO = Path(os.environ["CROWN_KEY_REPO_ROOT"]).resolve() if os.environ.get("CROWN_KEY_REPO_ROOT") else HERE.parents[5]
CANONICAL = REPO / "tools/contracts"
UPSTREAM = CANONICAL if (CANONICAL / "contract.py").is_file() else CACHE
if not (UPSTREAM / "contract.py").is_file():
    raise SystemExit("Run from the full lost-souls checkout, or set CROWN_KEY_REPO_ROOT to it. Original tools/contracts are required.")
PIN_FILE = HERE / "source-cache/SOURCES.json"
if PIN_FILE.is_file():
    pins = {r["path"].split("/")[-1]: r["sha256"] for r in json.loads(PIN_FILE.read_text())}
    for name in ("contract.py", "draw_svg.py"):
        observed = hashlib.sha256((UPSTREAM / name).read_bytes()).hexdigest()
        if observed != pins[name]:
            raise SystemExit("Canonical upstream drift: " + name + ". Use checkout at recorded main SHA or review a new tooling revision.")
sys.path.insert(0, str(UPSTREAM))
import contract as C
import draw_svg
import fitz
import numpy as np
from PIL import Image, ImageDraw

# Cached files are byte-identical. Restore their original repository-root
# semantics at runtime so provenance contains portable repository paths.
C.ROOT = REPO

EPS = 1e-8
VERSION = "CK-DESIGN-FALLBACK-R01"
COLORS = {"wall": (202, 198, 184), "slab": (162, 164, 169),
          "solid": (199, 196, 188), "core": (104, 132, 168),
          "glass": (116, 169, 188)}


_original_level_schedule = draw_svg.level_schedule


def readable_level_schedule(rep, stamp):
    """Preserve upstream CSV values; adapt only table wrapping/canvas size."""
    csv_text, _ = _original_level_schedule(rep, stamp)
    rows = list(csv.reader(io.StringIO("\n".join(csv_text.splitlines()[1:]))))
    headings = ["Level", "Floor z (m)", "Floor-to-floor (m)", "Clear (m)", "Slab (m)", "Masses present"]
    wrapped = []
    for r in rows[1:]:
        lines = textwrap.wrap(r[-1], width=44, break_long_words=False, break_on_hyphens=False) or ["-"]
        wrapped.append((r, lines, max(28, len(lines) * 19 + 10)))
    previous_h = draw_svg.H
    draw_svg.H = max(1000, 90 + 40 + sum(h for _, _, h in wrapped) + 190)
    try:
        sh = draw_svg.Sheet("Level schedule", "level schedule (wrapped presentation)", rep, stamp, (0, 0, 10, 10))
        xs = [90, 210, 380, 580, 760, 920]
        for x, text in zip(xs, headings):
            sh.text((x, 90), text, 13, draw_svg.INK, world=False, weight="bold")
        y = 126
        for row, lines, height in wrapped:
            for x, text in zip(xs, row[:-1]):
                sh.text((x, y), text or "-", 14, draw_svg.INK, world=False)
            for i, text in enumerate(lines):
                sh.text((xs[-1], y + i * 19), text, 12, draw_svg.INK, world=False)
            y += height
        return csv_text, sh.svg()
    finally:
        draw_svg.H = previous_h


draw_svg.level_schedule = readable_level_schedule


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


def write_json(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n")


def clean(poly):
    pts = []
    for p in poly:
        p = tuple(round(float(v), 8) for v in p)
        if not pts or math.dist(p, pts[-1]) > EPS:
            pts.append(p)
    if len(pts) > 1 and math.dist(pts[0], pts[-1]) < EPS:
        pts.pop()
    if len(pts) < 3 or abs(C.polygon_area(pts)) < EPS:
        return []
    if C.polygon_area(pts) < 0:
        pts.reverse()
    return pts


def halfplane(poly, normal, value, keep_positive=True):
    if not poly:
        return []
    def d(p):
        return (p[0] * normal[0] + p[1] * normal[1] - value) * (1 if keep_positive else -1)
    out = []
    for a, b in zip(poly, poly[1:] + poly[:1]):
        da, db = d(a), d(b)
        if da >= -EPS:
            out.append(a)
        if (da < -EPS and db > EPS) or (da > EPS and db < -EPS):
            t = da / (da - db)
            out.append((a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])))
    return clean(out)


def triangulate(poly):
    poly = clean(poly)
    if not poly:
        return []
    ids = list(range(len(poly)))
    result = []
    def cross(a, b, c):
        return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
    def inside(p, a, b, c):
        return min(cross(a, b, p), cross(b, c, p), cross(c, a, p)) >= -EPS
    while len(ids) > 3:
        found = False
        for j in range(len(ids)):
            a, b, c = (ids[(j - 1) % len(ids)], ids[j], ids[(j + 1) % len(ids)])
            if cross(poly[a], poly[b], poly[c]) <= EPS:
                continue
            if any(inside(poly[k], poly[a], poly[b], poly[c]) for k in ids if k not in (a, b, c)):
                continue
            result.append([poly[a], poly[b], poly[c]])
            ids.pop(j)
            found = True
            break
        if not found:
            raise ValueError("Cannot triangulate non-simple or numerically collapsed polygon")
    result.append([poly[k] for k in ids])
    return result


def subtract_convex(poly, cutter):
    """Disjoint convex pieces of poly minus convex CCW cutter."""
    remain = clean(poly)
    outside = []
    for a, b in zip(cutter, cutter[1:] + cutter[:1]):
        n = (-(b[1] - a[1]), b[0] - a[0])
        v = n[0] * a[0] + n[1] * a[1]
        part = halfplane(remain, n, v, False)
        if part:
            outside.append(part)
        remain = halfplane(remain, n, v, True)
        if not remain:
            break
    return outside


def cut_pieces(poly, cutters):
    pieces = triangulate(poly)
    for cutter in cutters:
        for triangle in triangulate(cutter):
            pieces = [q for p in pieces for q in subtract_convex(p, triangle)]
    return pieces


class Mesh:
    def __init__(self):
        self.objects = []

    def prism(self, name, poly, z0, z1, material, role, **props):
        poly = clean(poly)
        if not poly or z1 - z0 < EPS:
            return
        n = len(poly)
        vertices = [(x, y, z) for z in (z0, z1) for x, y in poly]
        triangles = triangulate(poly)
        lookup = {p: i for i, p in enumerate(poly)}
        faces = []
        for tri in triangles:
            a, b, c = [lookup[p] for p in tri]
            faces.extend([(c, b, a), (a + n, b + n, c + n)])
        for i in range(n):
            j = (i + 1) % n
            faces.extend([(i, j, j + n), (i, j + n, i + n)])
        self.objects.append({"name": name, "vertices": vertices, "triangles": faces,
                             "material": material, "role": role, "footprint": poly,
                             "z0": z0, "z1": z1, "props": props})

    def carved(self, name, poly, z0, z1, material, role, openings=(), holes=()):
        zs = sorted({z0, z1} | {max(z0, min(z1, o[k])) for o in openings for k in ("z0", "z1")})
        for zi, (a, b) in enumerate(zip(zs, zs[1:])):
            if b - a < EPS:
                continue
            active = [o["cut_band"] for o in openings if o["z0"] < b - EPS and o["z1"] > a + EPS]
            for pi, p in enumerate(cut_pieces(poly, list(holes) + active)):
                self.prism(f"{name}_Z{zi:02d}_P{pi:03d}", p, a, b, material, role)


def make_mesh(rep):
    mesh = Mesh()
    d = rep["derived"]
    cores = {c["id"]: c for c in d["cores"]}
    for m in d["masses"]:
        openings = [o for o in d["openings"] if o["host"] == m["id"]]
        if m["shell"] == "solid":
            mesh.carved("MASS_" + m["id"], m["footprint"], m["z0"], m["z1"], "solid", "solid", openings)
        else:
            outer, inner = m["footprint"], m["inner"]
            for i in range(len(outer)):
                j = (i + 1) % len(outer)
                ring = [outer[i], outer[j], inner[j], inner[i]]
                mesh.carved(f"WALL_{m['id']}_E{i:02d}", ring, m["z0"], m["z1"], "wall", "wall", openings)
            for sl in m["slabs"]:
                mesh.carved(sl["id"], sl["footprint"], sl["z0"], sl["z1"], "slab", sl["kind"],
                            holes=[cores[c]["footprint"] for c in sl.get("holes", [])])
    for o in d["openings"]:
        if o.get("glazing_band"):
            mesh.prism("GLZ_" + o["id"], o["glazing_band"], o["z0"], o["z1"], "glass", "glazing")
    for c in d["cores"]:
        mesh.carved("CORE_" + c["id"], c["footprint"], c["z0"], c["z1"], "core", "core")
    return mesh


def clean_plans(rep, stamp, out):
    """Presentation sheets only: exact existing polygons, keyed schedules."""
    d = rep["derived"]
    files, index = {}, []
    levels = [lv for lv in d["levels"] if any(m["shell"] == "hollow" and lv["level_id"] in m["levels"] for m in d["masses"])]
    for lv in levels:
        rooms = [m for m in d["masses"] if m["shell"] == "hollow" and lv["level_id"] in m["levels"]]
        # A clean overview and separate enlarged room sheets keep the selected
        # slice legible. Original all-level cut drawings remain an appendix.
        scopes = [("OVERVIEW", rooms)] + [(m["id"], [m]) for m in rooms]
        for scope, focus in scopes:
            z = lv["z"]
            pts = [p for m in focus for p in m["footprint"]]
            x0, y0 = min(p[0] for p in pts) - 2, min(p[1] for p in pts) - 2
            x1, y1 = max(p[0] for p in pts) + 2, max(p[1] for p in pts) + 2
            feature_rows = [o for o in d["openings"] if o["host"] in {m["id"] for m in focus} and o["level_id"] == lv["level_id"]]
            visible = [m for m in d["masses"] if m["z0"] <= z + .1 < m["z1"]
                       or (m["kind"] == "furniture_proxy" and m["z0"] <= z + .001 < m["z1"])
                       or (m["kind"] in ("deck", "paving") and abs(m["z1"] - z) < .01)]
            props = [m for m in visible if m["kind"] == "furniture_proxy" and any(C.point_in_polygon((sum(p[0] for p in m["footprint"])/len(m["footprint"]),sum(p[1] for p in m["footprint"])/len(m["footprint"])), r["footprint"]) for r in focus)]
            right_rows = len(focus) + len(feature_rows) + len(props) + 7
            W, H = 2400, max(1600, 230 + right_rows * 30)
            s = min(1440 / max(x1 - x0, 1), (H - 400) / max(y1 - y0, 1))
            ox = 100 + (1440 - (x1 - x0) * s) / 2 - x0 * s
            oy = 160 + ((H - 400) - (y1 - y0) * s) / 2 + y1 * s
            def P(p): return ox + p[0] * s, oy - p[1] * s
            def poly(fp):
                # Geometric crop, rather than SVG clipPath only: MuPDF's SVG
                # converter does not preserve every clipPath in converted PDF.
                pts=clean(fp)
                for n,v in [((1,0),x0),((-1,0),-x1),((0,1),y0),((0,-1),-y1)]:
                    pts=halfplane(pts,n,v)
                return " ".join(f"{P(p)[0]:.3f},{P(p)[1]:.3f}" for p in pts)
            def text(x,y,body,size=20,color="#17212b",anchor="start"):
                return f'<text x="{x:.3f}" y="{y:.3f}" font-family="Helvetica,Arial,sans-serif" font-size="{size}" fill="{color}" text-anchor="{anchor}">{escape(str(body))}</text>'
            parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">',
                     '<rect width="100%" height="100%" fill="white"/>',
                     '<metadata>'+escape(json.dumps({"stamp":stamp,"view":"clean keyed furnished footprint plan","level":lv["level_id"],"scope":scope},sort_keys=True))+'</metadata>',
                     text(70,55,f"PROPOSED DESIGN | {stamp['asset_id']} | {lv['level_id']} @ {z:g} m | {scope}",30),
                     text(70,92,"Exact proposed footprint geometry and furniture proxies. Front -Y is down. Dimensions in metres; print scaling is variable.",21),
                     f'<defs><clipPath id="plan"><rect x="70" y="125" width="1510" height="{H-310}"/></clipPath></defs><g clip-path="url(#plan)">']
            # Fill rooms first, then fixtures/closed masses, then wall cut bands.
            for m in visible:
                if m["shell"] == "hollow":
                    parts.append(f'<polygon points="{poly(m["footprint"])}" fill="#faf7ee" stroke="#233142" stroke-width="2"/>')
                else:
                    fill = "#d5e4ec" if m["kind"] == "furniture_proxy" else ("#f3f0e8" if m["kind"] in ("deck","paving") else "#b2b9c2")
                    parts.append(f'<polygon points="{poly(m["footprint"])}" fill="{fill}" stroke="#536478" stroke-width="1.5"/>')
            for m in visible:
                if m["shell"] == "hollow":
                    outer,inner=m["footprint"],m["inner"]
                    for j in range(len(outer)):
                        k=(j+1)%len(outer)
                        parts.append(f'<polygon points="{poly([outer[j],outer[k],inner[k],inner[j]])}" fill="#233142"/>')
            for core in d["cores"]:
                if core["z0"] <= z + .1 < core["z1"]:
                    parts.append(f'<polygon points="{poly(core["footprint"])}" fill="#6886a7" stroke="#233142" stroke-width="2"/>')
            for o in d["openings"]:
                if o["level_id"] == lv["level_id"]:
                    fill = "#9dcee2" if o["use"] == "window" else "white"
                    parts.append(f'<polygon points="{poly(o["cut_band"])}" fill="{fill}" stroke="#168561" stroke-width="1.5"/>')
            for i,m in enumerate(focus,1):
                p = P((sum(p[0] for p in m["inner"])/len(m["inner"]),sum(p[1] for p in m["inner"])/len(m["inner"])))
                parts.append(text(*p,f"R{i:02d}",26,"#17212b","middle"))
            for i,o in enumerate(feature_rows,1):
                mid = ((o["p0"][0]+o["p1"][0])/2+o["normal"][0]*1.1,(o["p0"][1]+o["p1"][1])/2+o["normal"][1]*1.1)
                px,py=P(mid)
                parts.append(f'<circle cx="{px:.3f}" cy="{py-5:.3f}" r="14" fill="white" stroke="#168561"/>')
                parts.append(text(px,py+1,str(i),17,"#116348","middle"))
            for i,m in enumerate(props,1):
                p=P((sum(p[0] for p in m["footprint"])/len(m["footprint"]),sum(p[1] for p in m["footprint"])/len(m["footprint"])))
                parts.append(text(*p,f"F{i:02d}",15,"#2e5266","middle"))
            parts.append('</g>')
            # Overall drawing extent remains dimensioned; each keyed row below
            # preserves the actual usable inner room width/depth for review.
            for a,b,label in [((x0+2,y0+2),(x1-2,y0+2),f"{x1-x0-4:.2f} m"),((x0+2,y0+2),(x0+2,y1-2),f"{y1-y0-4:.2f} m")]:
                pa,pb=P(a),P(b)
                parts.append(f'<line x1="{pa[0]}" y1="{pa[1]}" x2="{pb[0]}" y2="{pb[1]}" stroke="#bc7638" stroke-width="2" stroke-dasharray="9 6"/>')
                parts.append(text((pa[0]+pb[0])/2,(pa[1]+pb[1])/2+24,label,20,"#935520","middle"))
            rx,ry=1640,160
            parts.append(text(rx,ry,"ROOM KEYS / CLEAR INNER EXTENTS",22));ry+=38
            for i,m in enumerate(focus,1):
                xx=[p[0] for p in m["inner"]];yy=[p[1] for p in m["inner"]]
                parts.append(text(rx,ry,f"R{i:02d} {m['id']} | {max(xx)-min(xx):.2f} x {max(yy)-min(yy):.2f} m",19));ry+=30
            parts.append(text(rx,ry+18,"OPENINGS | KEY : ID : WIDTH x HEIGHT / SILL",21));ry+=58
            for i,o in enumerate(feature_rows,1):
                parts.append(text(rx,ry,f"{i:02d} {o['id']} : {o['width']:g} x {o['height']:g} / {o['sill']:g} m",18));ry+=30
            if props:
                parts.append(text(rx,ry+18,"FURNITURE / FIXTURE FOOTPRINT PROXIES",21));ry+=58
                for i,m in enumerate(props,1):
                    parts.append(text(rx,ry,f"F{i:02d} {m['id']}",18));ry+=30
            parts += [text(70,H-105,"Green keyed cuts are actual openings; blue panels are blocking glazing. Blue-grey solids/cores are closed geometry.",20),
                      text(70,H-75,"Furniture silhouettes include low objects omitted by the 1.2 m cut plan. They are proposed proxies, not proof of capsule/door-swing clearance.",20),
                      text(70,H-45,f"Contract {stamp['contract_revision']} | sha256 {stamp['contract_sha256']} | {VERSION} | NOT ACCEPTED BUILD REFERENCE",18),'</svg>']
            name=f"CLEAN_PLAN_{lv['level_id']}_{scope}.svg"
            txt="\n".join(parts)+"\n";(out/name).write_text(txt);files[name]=hashlib.sha256(txt.encode()).hexdigest()
            index.append({"file":name,"level_id":lv["level_id"],"scope":scope,"type":"supplemental clean keyed furnished footprint plan","source":"same contract.analyse derived geometry","approval":None})
    write_json(out.parent/'CLEAN_PLAN_INDEX.json',{"stamp":stamp,"sheets":index,"status":"PROPOSED_PRESENTATION_SUPPLEMENT_NOT_CLEARANCE_ACCEPTANCE"})
    return files


def export_obj(mesh, out, prefix, stamp):
    lines = ["# PROPOSED DESIGN CANDIDATE - NOT ACCEPTED / NOT ENGINE VERIFIED",
             "# metres; X local right, Y local rear, front -Y, Z up",
             "# contract_sha256=" + stamp["contract_sha256"], "mtllib " + prefix + ".mtl"]
    offset = 1
    for o in mesh.objects:
        lines.extend(["o " + o["name"], "usemtl " + o["material"]])
        lines += ["v " + " ".join(f"{v:.8f}" for v in p) for p in o["vertices"]]
        lines += ["f " + " ".join(str(i + offset) for i in tri) for tri in o["triangles"]]
        offset += len(o["vertices"])
    (out / (prefix + ".obj")).write_text("\n".join(lines) + "\n")
    mtl = ["# Neutral preview materials only; no production texture acceptance"]
    for name, col in COLORS.items():
        mtl.extend(["newmtl " + name, "Kd " + " ".join(f"{v / 255:.6f}" for v in col), "Ks 0.05 0.05 0.05", "Ns 12", "d 1.0"])
    (out / (prefix + ".mtl")).write_text("\n".join(mtl) + "\n")


def scene_triangles(mesh):
    tris, cols = [], []
    for o in mesh.objects:
        vertices = np.asarray(o["vertices"], dtype=float)
        for f in o["triangles"]:
            tris.append(vertices[list(f)])
            cols.append(COLORS[o["material"]])
    return np.asarray(tris), np.asarray(cols)


def ray_distances(tris, origin, direction):
    v0, e1, e2 = tris[:, 0], tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0]
    p = np.cross(np.asarray(direction), e2)
    det = np.einsum("ij,ij->i", e1, p)
    inv = np.divide(1.0, det, out=np.zeros_like(det), where=np.abs(det) > EPS)
    tvec = np.asarray(origin) - v0
    u = np.einsum("ij,ij->i", tvec, p) * inv
    q = np.cross(tvec, e1)
    v = q @ np.asarray(direction) * inv
    t = np.einsum("ij,ij->i", e2, q) * inv
    good = (np.abs(det) > EPS) & (u >= -EPS) & (v >= -EPS) & (u + v <= 1 + EPS) & (t > EPS)
    return t[good]


def validate_mesh(mesh, rep):
    triangles, _ = scene_triangles(mesh)
    vertices = triangles.reshape(-1, 3)
    negative, unclosed = [], []
    for o in mesh.objects:
        vv = np.asarray(o["vertices"])
        tr = vv[np.asarray(o["triangles"])]
        volume = float(np.sum(np.einsum("ij,ij->i", tr[:, 0], np.cross(tr[:, 1], tr[:, 2]))) / 6)
        if volume <= EPS:
            negative.append(o["name"])
        edges = {}
        for tri in o["triangles"]:
            for a, b in zip(tri, tri[1:] + tri[:1]):
                k = tuple(sorted((a, b)))
                edges[k] = edges.get(k, 0) + 1
        if any(v != 2 for v in edges.values()):
            unclosed.append(o["name"])
    rays, support = [], []
    for o in rep["derived"]["openings"]:
        p0, p1, n = np.asarray(o["p0"]), np.asarray(o["p1"]), np.asarray(o["normal"])
        mid = (p0 + p1) / 2
        z = o["z0"] + min(1.0, o["height"] / 2)
        origin = [*(mid + n * 0.05), z]
        hits = ray_distances(triangles, origin, [-n[0], -n[1], 0])
        near = hits[hits < o["depth"] + 0.2]
        expected_clear = o["use"] in ("door", "portal")
        rays.append({"opening": o["id"], "probe": "center at +1m (or half height)", "expected_clear": expected_clear,
                     "observed_clear": not len(near), "pass": bool((not len(near)) == expected_clear)})
        if o["passable"]:
            for label, delta in (("before", 0.1), ("within", -o["depth"] / 2), ("after", -o["depth"] - 0.1)):
                p = mid + n * delta
                hit = ray_distances(triangles, [*p, o["z0"] + 0.25], [0, 0, -1])
                floor_z = None if not len(hit) else round(o["z0"] + 0.25 - float(min(hit)), 6)
                # An exterior before station need not have a declared apron.
                declared = any(C.point_in_polygon(p, m["footprint"]) for m in rep["derived"]["masses"])
                required = label != "before" or declared
                passed = not required or (floor_z is not None and abs(floor_z - o["z0"]) < 0.005)
                support.append({"opening": o["id"], "station": label, "required": required, "expected_z_m": o["z0"], "observed_z_m": floor_z, "pass": passed})
    duplicates = []
    surfaces = [o for o in mesh.objects if o["role"] in ("floor", "roof", "solid", "core")]
    for i, a in enumerate(surfaces):
        for b in surfaces[i + 1:]:
            if abs(a["z1"] - b["z1"]) > 0.00001:
                continue
            p = a["footprint"]
            for x, y in zip(b["footprint"], b["footprint"][1:] + b["footprint"][:1]):
                n = (-(y[1] - x[1]), y[0] - x[0])
                p = halfplane(p, n, n[0] * x[0] + n[1] * x[1])
                if not p:
                    break
            if p and abs(C.polygon_area(p)) > 1e-6:
                duplicates.append({"a": a["name"], "b": b["name"], "overlap_m2": round(abs(C.polygon_area(p)), 7)})
    ok = not negative and not unclosed and not duplicates and all(r["pass"] for r in rays + support)
    return {"verification": "PASS" if ok else "FAIL", "method": "fallback OBJ mesh checks; not Blender/Unreal checks",
            "mesh_extent_m": {"min": vertices.min(axis=0).round(6).tolist(), "max": vertices.max(axis=0).round(6).tolist()},
            "objects": len(mesh.objects), "triangles": len(triangles), "nonpositive_volume_primitives": negative,
            "nonmanifold_primitives": unclosed, "opening_center_rays": rays, "threshold_center_floor_support": support,
            "duplicate_upward_floor_areas": duplicates,
            "limits": ["Center probes only; not full capsule sweeps or route acceptance", "Adjacent closed prisms retain coincident internal faces", "No Blender export/round-trip or Unreal import executed"]}


def neutral_render(mesh, cam, path, stamp):
    w, h = cam.get("resolution_px", [1280, 800])
    pos, target = np.array(cam["location_m"], dtype=float), np.array(cam["target_m"], dtype=float)
    forward = target - pos
    forward /= np.linalg.norm(forward)
    up = np.array([0.0, 0.0, 1.0])
    if abs(forward @ up) > 0.995:
        up = np.array([0.0, 1.0, 0.0])
    right = np.cross(forward, up)
    right /= np.linalg.norm(right)
    up = np.cross(right, forward)
    tris, colors = scene_triangles(mesh)
    # Clip triangles against the actual camera near plane. Rejecting a triangle
    # with only one vertex behind the eye would erase room walls/ceilings.
    clipped, clipped_colors = [], []
    for tri, color in zip(tris, colors):
        pts = list(tri)
        result = []
        for a, b in zip(pts, pts[1:] + pts[:1]):
            da, db = float((a - pos) @ forward) - .05, float((b - pos) @ forward) - .05
            if da >= 0:
                result.append(a)
            if (da < 0 < db) or (db < 0 < da):
                result.append(a + da / (da - db) * (b - a))
        for i in range(1, len(result) - 1):
            clipped.append([result[0], result[i], result[i + 1]])
            clipped_colors.append(color)
    tris, colors = np.asarray(clipped), np.asarray(clipped_colors)
    rel = tris - pos
    depths = rel @ forward
    x, y = rel @ right, rel @ up
    projection = cam.get("projection", "perspective")
    if projection == "orthographic":
        s = w / cam["orthographic_width_m"]
        xx, yy = w / 2 + x * s, h / 2 - y * s
    else:
        focal = cam.get("lens_mm", 35) / cam.get("sensor_width_mm", 36) * w
        xx, yy = w / 2 + x / depths * focal, h / 2 - y / depths * focal
    rgb = np.full((h, w, 3), [232, 232, 226], dtype=np.uint8)
    zbuf = np.full((h, w), np.inf)
    light = np.array([-0.4, -0.6, 0.8]); light /= np.linalg.norm(light)
    for tri, dep, sx, sy, color in zip(tris, depths, xx, yy, colors):
        x0, x1 = max(0, int(np.floor(min(sx)))), min(w - 1, int(np.ceil(max(sx))))
        y0, y1 = max(0, int(np.floor(min(sy)))), min(h - 1, int(np.ceil(max(sy))))
        if x1 < x0 or y1 < y0:
            continue
        denominator = (sy[1] - sy[2]) * (sx[0] - sx[2]) + (sx[2] - sx[1]) * (sy[0] - sy[2])
        if abs(denominator) < EPS:
            continue
        gx, gy = np.meshgrid(np.arange(x0, x1 + 1) + .5, np.arange(y0, y1 + 1) + .5)
        a = ((sy[1] - sy[2]) * (gx - sx[2]) + (sx[2] - sx[1]) * (gy - sy[2])) / denominator
        b = ((sy[2] - sy[0]) * (gx - sx[2]) + (sx[0] - sx[2]) * (gy - sy[2])) / denominator
        c = 1 - a - b
        zz = a * dep[0] + b * dep[1] + c * dep[2] if projection == "orthographic" else 1 / (a / dep[0] + b / dep[1] + c / dep[2])
        current = zbuf[y0:y1 + 1, x0:x1 + 1]
        mask = (a >= -EPS) & (b >= -EPS) & (c >= -EPS) & (zz < current)
        normal = np.cross(tri[1] - tri[0], tri[2] - tri[0]); normal /= max(EPS, np.linalg.norm(normal))
        shade = .65 + .35 * abs(float(normal @ light))
        rgb[y0:y1 + 1, x0:x1 + 1][mask] = (color * shade).astype(np.uint8)
        current[mask] = zz[mask]
    im = Image.fromarray(rgb)
    draw = ImageDraw.Draw(im)
    draw.rectangle((0, h - 42, w, h), fill=(25, 31, 39))
    draw.text((14, h - 32), f"PROPOSED DESIGN | {stamp['asset_id']} | {cam['id']} | NOT ACCEPTED BUILD REFERENCE", fill=(245, 245, 240))
    draw.text((14, h - 16), "Neutral CPU z-buffer; exact proposed mesh; no finishes / no placed surroundings", fill=(201, 207, 214))
    im.save(path, optimize=True)
    return {**cam, "source_tool": VERSION + " / CPU z-buffer", "camera_basis": {"right": right.tolist(), "up": up.tolist(), "forward": forward.tolist()},
            "render_file": path.name, "render_sha256": sha(path), "status": "CONCEPT", "accepted_scope": None}


def camera_set(mesh, schedule):
    vertices = np.asarray([p for o in mesh.objects for p in o["vertices"]])
    mn, mx = vertices.min(axis=0), vertices.max(axis=0)
    center, span = (mn + mx) / 2, float(max(mx - mn))
    cams = [{"id": "NEUTRAL_EXT_FRONT_LEFT", "location_m": (center + np.array([-1.2, -1.6, 1.1]) * span).tolist(),
             "target_m": center.tolist(), "projection": "orthographic", "orthographic_width_m": span * 1.75, "resolution_px": [1280, 800]},
            {"id": "NEUTRAL_EXT_FRONT_RIGHT", "location_m": (center + np.array([1.2, -1.6, .65]) * span).tolist(),
             "target_m": center.tolist(), "projection": "orthographic", "orthographic_width_m": span * 1.75, "resolution_px": [1280, 800]}]
    cams.append({"id": "NEUTRAL_EXT_REAR_RIGHT", "location_m": (center + np.array([1.2, 1.6, .85]) * span).tolist(),
                 "target_m": center.tolist(), "projection": "orthographic", "orthographic_width_m": span * 1.75, "resolution_px": [1280, 800]})
    for c in cams:
        loc, target = np.asarray(c["location_m"]), np.asarray(c["target_m"])
        forward = target - loc; forward /= np.linalg.norm(forward)
        right = np.cross(forward, [0., 0., 1.]); right /= np.linalg.norm(right)
        up = np.cross(right, forward)
        x, y = (vertices - target) @ right, (vertices - target) @ up
        aspect = c["resolution_px"][0] / c["resolution_px"][1]
        c["orthographic_width_m"] = round(max(2 * np.max(np.abs(x)), 2 * np.max(np.abs(y)) * aspect) * 1.20, 6)
        c["framing"] = "Full projected proposed mesh extent plus20percent margin; footer reserved within margin"
    if schedule:
        raw = json.loads(schedule.read_text())
        if isinstance(raw, dict):
            raw = raw.get("cameras") or raw.get("views") or []
        for c in raw:
            if c.get("location_m") is not None and c.get("target_m") is not None:
                cams.append({"projection": "perspective", "lens_mm": 35, "sensor_width_mm": 36,
                             "resolution_px": [1280, 800], **c, "id": c.get("id") or c.get("camera_id") or c.get("view_id")})
    return cams


def build(contract, out, cameras=None):
    out.mkdir(parents=True, exist_ok=True)
    data, prov = C.load(contract)
    rep, stamp = C.analyse(data), C.stamp(data, prov)
    if rep["result"] == "INVALID" or not rep["derived"]["masses"]:
        raise ValueError("Upstream contract INVALID: " + "; ".join(rep["errors"]))
    # Remove only byte-verified outputs from our previous manifest. Preserve
    # hand edits, unrelated files and source files; avoid stale sheets/cameras
    # appearing in a regenerated candidate when a level or view is removed.
    previous = out / "MANIFEST.json"
    if previous.exists():
        prior = json.loads(previous.read_text())
        if prior.get("builder") != VERSION:
            raise ValueError("Output manifest belongs to another tool; refusing replacement")
        old_paths = []
        for rel, rec in prior.get("files", {}).items():
            p = out / rel
            if not p.resolve().is_relative_to(out.resolve()) or p.is_symlink():
                raise ValueError("Unsafe path in previous generated manifest: " + rel)
            if p.exists() and sha(p) != rec["sha256"]:
                raise ValueError("Generated output was changed by another author; preserve/review it: " + rel)
            if p.is_file():
                old_paths.append(p)
        for p in old_paths:
            p.unlink()
        previous.unlink()
    prefix = C.output_prefix(data)
    drawing_dir = out / "drawings"
    drawing_manifest = draw_svg.generate(contract, drawing_dir)
    clean_files = clean_plans(rep, stamp, drawing_dir)
    pdf = fitz.open()
    sheets = []
    for name in list(sorted(clean_files)) + list(sorted(drawing_manifest["files"])):
        p = drawing_dir / name
        if p.suffix != ".svg":
            continue
        if "_PLAN_" in name and not name.startswith("CLEAN_PLAN_"):
            continue  # raw cut plans remain the SVG audit appendix; keyed plans are primary
        svg = fitz.open(stream=p.read_bytes(), filetype="svg")
        one = fitz.open(stream=svg.convert_to_pdf(), filetype="pdf")
        pdf.insert_pdf(one)
        sheets.append(p.name)
    pdf.set_metadata({"title": f"PROPOSED DESIGN / {data['asset_id']} / {data['contract_revision']}",
                      "subject": "Not accepted for construction or engine import", "author": "Codex / deterministic existing contract drawings"})
    pdf.save(out / (prefix + "_DRAWING_SET.pdf"), garbage=4, deflate=True, no_new_id=True)
    pdf.close()
    mesh = make_mesh(rep)
    export_obj(mesh, out, prefix, stamp)
    verification = validate_mesh(mesh, rep)
    write_json(out / "GEOMETRY_CHECKS.json", verification)
    write_json(out / "ANALYSIS.json", {"stamp": stamp, **rep})
    gate = C.issue_gate(data, prov, "docs/crown-key-production/R02/production-run/R01/" + contract.parent.name + "/BUILDING_DIMENSIONS.json")
    write_json(out / "ISSUE_GATE.json", {"issuable": gate["issuable"], "problems": gate["problems"], "note": "Design candidate in docs; intentional refusal. Analysis COMPLETE is not creator or engine acceptance."})
    view_dir = out / "neutral-views"; view_dir.mkdir(exist_ok=True)
    records = [neutral_render(mesh, c, view_dir / (c["id"] + ".png"), stamp) for c in camera_set(mesh, cameras)]
    write_json(out / "SAVED_CAMERAS.json", {"stamp": stamp, "model_file": prefix + ".obj", "model_sha256": sha(out / (prefix + ".obj")),
               "world_frame": data["coordinate_frame"], "views": records, "comparison": "not yet compared with finished imagery", "approval": None})
    with (out / "OPENINGS_DERIVED.csv").open("w", newline="") as f:
        fields = ["id", "host", "edge", "level_id", "use", "width", "height", "sill", "z0", "z1", "passable", "collision"]
        w = csv.DictWriter(f, fields, extrasaction="ignore"); w.writeheader(); w.writerows(rep["derived"]["openings"])
    # Replay uses upstream tools on the real checkout, never this fallback's OBJ.
    (out / "REBUILD_BLENDER.sh").write_text("#!/usr/bin/env sh\nset -eu\n# Run at repo root with Blender 5.x installed; not executed in this environment.\nblender -b -P tools/contracts/blockout.py -- " + C.rel_path(contract) + " --out " + C.rel_path(out) + "/blender --views\n")
    manifest = {"status": "PROPOSED_DESIGN_CANDIDATE_NOT_ENGINE_VERIFIED", "builder": VERSION,
                "builder_sha256": sha(__file__),
                "upstream_source_sha256": {p: sha(UPSTREAM / p) for p in ("contract.py", "draw_svg.py")},
                "dependencies": {"python": sys.version.split()[0], "numpy": np.__version__, "PyMuPDF": fitz.VersionBind},
                "contract_sha256": stamp["contract_sha256"],
                "source_file_sha256": sha(contract), "upstream_tool_version": C.TOOL_VERSION, "analysis_result": rep["result"],
                "geometry_verification": verification["verification"], "issue_gate_issuable": gate["issuable"],
                "drawing_sheets": sheets, "blender_executed": False, "unreal_executed": False,
                "files": {p.relative_to(out).as_posix(): {"sha256": sha(p), "bytes": p.stat().st_size} for p in sorted(out.rglob("*")) if p.is_file() and p.name != "MANIFEST.json"}}
    write_json(out / "MANIFEST.json", manifest)
    print(json.dumps({"asset": data["asset_id"], "analysis": rep["result"], "geometry": verification["verification"], "sheets": len(sheets), "objects": len(mesh.objects), "neutral_views": len(records), "out": str(out)}))
    return 0 if verification["verification"] == "PASS" else 1


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("contract", type=Path)
    ap.add_argument("--out", type=Path, required=True)
    ap.add_argument("--cameras", type=Path)
    a = ap.parse_args()
    sys.exit(build(a.contract.resolve(), a.out.resolve(), a.cameras.resolve() if a.cameras else None))
