"""Crown Landmark ENTRANCE module (round 2): grand pointed entry arch + tall glazed pointed lobby facade (z 0-46), portal, canopy,
two steep mirrored arch blades (Entry_arch_blade_L/R) from the front basins meeting at z~50, +36 terrace with ribbed dome/lantern,
two oval water basins with thick ivory collars, forecourt.

Frame: metres, Z up, FRONT = -Y, X = right. Scope |x| <= ~62 m at the front. Object names Entry_*.
Labels: target = R06 numbers (arch 18x14, portal 8x4.5, basins at +-58,-40); proposed = builder choices in P below.
"""
import math
import os
import sys
import json
import bpy
from mathutils import Vector
import cl_common as C

COLLECTION = "Entrance"

P = dict(
    # --- target (R06)
    arch_w=C.ENTRY_ARCH[0], arch_h=C.ENTRY_ARCH[1],         # 18 x 14 clear
    portal_w=C.ENTRY_PORTAL[0], portal_h=C.ENTRY_PORTAL[1],  # 8 x 4.5 clear
    basin_c=((-58.0, -42.0), (58.0, -42.0)),   # R3: rib feet (27 x 8.2 at +-58,-40) stand inside; centre shifted 2 m forward
    # --- proposed
    bay_hw=21.95,           # open front bay half width (podium keeps |x|<=22 open)
    arch_y=-50.0,           # arch plane (front face of the ivory arch band)
    glass_y=-44.0,          # glazed lobby facade plane
    back_y=-33.2,           # lobby back wall front face (podium tier-3 notch edge is at -32.6)
    band=2.2,               # ivory arch band width
    facade_w=43.8, facade_h=52.0,   # tall glazed pointed-arch lobby facade (fills the open bay, rises through the tiers)
    terrace_z=36.0,         # +36 terrace / apron top
    apron_t=0.8, apron_back_y=-39.6,   # apron meets the podium tier-2 notch edge
    # grand arch blades (two mirrored objects)
    blade_foot=(43.5, -42.0), blade_apex_z=41.0, blade_apex_y=-50.6,
    blade_vis=(9.4, 7.0),   # visible (front-view) band width foot -> apex
    blade_depth=(4.4, 3.4), # front-to-back thickness foot -> apex
    jamb=0.40,              # portal frame member size; clear width is 2*(4.02)
    dome_c=(0.0, -49.2), dome_r=4.9, dome_h=4.2, dome_z=17.0,   # on the entry-arch apex
    basin_a=16.0, basin_b=9.0,   # water ellipse semi-axes
)

_last_verify = {}


# ---------------------------------------------------------------- geometry helpers ----------------
def merge(parts):
    V, F = [], []
    for v, f in parts:
        o = len(V)
        V += [tuple(p) for p in v]
        F += [tuple(i + o for i in fc) for fc in f]
    return V, F


def box(x0, x1, y0, y1, z0, z1):
    v = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]
    f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
    return v, f


def prism(poly, z0, z1):
    """Extrude a plan polygon [(x,y)...] (any winding) from z0 to z1 (ngon caps)."""
    n = len(poly)
    v = [(x, y, z0) for x, y in poly] + [(x, y, z1) for x, y in poly]
    f = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))]
    for i in range(n):
        j = (i + 1) % n
        f.append((i, j, j + n, i + n))
    return v, f


def ellipse_pts(cx, cy, a, b, z, n=56):
    return [(cx + a * math.cos(2 * math.pi * i / n), cy + b * math.sin(2 * math.pi * i / n), z) for i in range(n)]


def arch_half(width, height, off=0.0, n=22):
    """Right-half points (x,z) of the two-centre pointed arch offset outward by `off` (concentric)."""
    hw = width / 2
    c = (height ** 2 - hw ** 2) / (2 * hw)
    Ro = hw + c + off
    a_end = math.acos(max(-1.0, min(1.0, c / Ro)))
    return [(-c + Ro * math.cos(a_end * i / n), Ro * math.sin(a_end * i / n)) for i in range(n + 1)]


def arch_full(width, height, off=0.0, n=22):
    """Left springing -> apex -> right springing."""
    r = arch_half(width, height, off, n)
    left = [(-x, z) for x, z in r]
    return left + list(reversed(r))[1:]


def arch_z(x, width, height):
    hw = width / 2
    c = (height ** 2 - hw ** 2) / (2 * hw)
    R = hw + c
    t = R * R - (abs(x) + c) ** 2
    return math.sqrt(t) if t > 0 else 0.0


def arch_x_at(z, width, height):
    hw = width / 2
    c = (height ** 2 - hw ** 2) / (2 * hw)
    R = hw + c
    t = R * R - z * z
    return math.sqrt(t) - c if t > 0 else 0.0


def band_extrude(inner, outer, y0, y1):
    """Arch ring: inner/outer outlines (x,z) same length, extruded y0..y1. Closed shell."""
    m = len(inner)
    V = []
    for y in (y0, y1):
        V += [(x, y, z) for x, z in inner]
        V += [(x, y, z) for x, z in outer]
    I0, O0, I1, O1 = 0, m, 2 * m, 3 * m
    F = []
    for i in range(m - 1):
        F.append((O0 + i, O0 + i + 1, I0 + i + 1, I0 + i))          # front cap
        F.append((O1 + i, O1 + i + 1, I1 + i + 1, I1 + i))          # back cap
        F.append((I0 + i, I0 + i + 1, I1 + i + 1, I1 + i))          # soffit
        F.append((O0 + i, O0 + i + 1, O1 + i + 1, O1 + i))          # extrados
    for k in (0, m - 1):                                            # springing feet
        F.append((I0 + k, O0 + k, O1 + k, I1 + k))
    return V, F


def sheet_columns(xs, zlo, zhi, y):
    """Flat sheet in the XZ plane at y; per-x bottom/top."""
    V, F = [], []
    for x in xs:
        V += [(x, y, zlo(x)), (x, y, zhi(x))]
    for i in range(len(xs) - 1):
        a = 2 * i
        F.append((a, a + 2, a + 3, a + 1))
    return V, F


def prism_columns(xs, zlo, zhi, y0, y1):
    rings = [[(x, y0, zlo(x)), (x, y1, zlo(x)), (x, y1, zhi(x)), (x, y0, zhi(x))] for x in xs]
    return C.loft(rings)


_SEC = [(1.0, 0.55), (0.55, 1.0), (-0.55, 1.0), (-1.0, 0.55), (-1.0, -0.55), (-0.55, -1.0), (0.55, -1.0), (1.0, -0.55)]


def sweep(path_pts, widths, thicks, up=(0, 0, 1)):
    """Chamfered-rectangle section swept along a polyline (width along tangent x up, thickness normal to it)."""
    rings = []
    up = Vector(up)
    n = len(path_pts)
    for i, p in enumerate(path_pts):
        tan = (Vector(path_pts[min(i + 1, n - 1)]) - Vector(path_pts[max(i - 1, 0)])).normalized()
        side = tan.cross(up)
        if side.length < 1e-6:
            side = Vector((1, 0, 0))
        side.normalize()
        nor = side.cross(tan).normalized()
        c = Vector(p)
        hw, ht = widths[i] / 2, thicks[i] / 2
        rings.append([tuple(c + side * hw * a + nor * ht * b) for a, b in _SEC])
    return C.loft(rings)


# ---------------------------------------------------------------- parts ---------------------------
def build_arch_porch(coll):
    w, h, b = P["arch_w"], P["arch_h"], P["band"]
    inner = arch_full(w, h, 0.0)
    outer = arch_full(w, h, b)
    v, f = band_extrude(inner, outer, P["arch_y"], P["glass_y"] - 0.3)
    v2, f2 = band_extrude(outer, arch_full(w, h, b + 1.3), P["arch_y"] - 0.5, P["arch_y"] + 1.0)
    v, f = merge([(v, f), (v2, f2)])
    return C.make_object("Entry_arch_band", v, f, C.mat("ivory"), coll, smooth_shade=False)


def facade_xs():
    hw = P["facade_w"] / 2
    s = set()
    k = -hw
    while k <= hw + 1e-6:
        s.add(round(k, 3))
        k += 1.0
    s.add(round(hw, 3)); s.add(round(-hw, 3))
    for a in (0.5, 1.0, 1.5):
        s.add(round(hw - a, 3)); s.add(round(-hw + a, 3))
    for x in (0.0, -P["portal_w"] / 2 - 0.42, P["portal_w"] / 2 + 0.42):
        s.add(round(x, 3))
    return sorted(s)


def build_glazing(coll):
    fw, fh = P["facade_w"], P["facade_h"]
    pj = P["portal_w"] / 2 + 0.42
    xs = facade_xs()
    top = lambda x: arch_z(x, fw, fh) - 0.02
    segs = [([x for x in xs if x <= -pj + 1e-6], lambda x: 0.0),
            ([x for x in xs if -pj - 1e-6 <= x <= pj + 1e-6], lambda x: P["portal_h"]),
            ([x for x in xs if x >= pj - 1e-6], lambda x: 0.0)]
    parts = [sheet_columns(s, lo, top, P["glass_y"]) for s, lo in segs]
    v, f = merge(parts)
    return C.make_object("Entry_lobby_glazing", v, f, C.mat("glass"), coll, smooth_shade=False)


def build_mullions(coll):
    fw, fh = P["facade_w"], P["facade_h"]
    y0, y1 = P["glass_y"] - 0.2, P["glass_y"] + 0.2
    lintel_top = P["portal_h"] + 0.42
    pj = P["portal_w"] / 2 + 0.42
    parts = []
    x = -20.0
    while x <= 20.0 + 1e-6:
        zt = arch_z(x, fw, fh) - 0.05
        zb = lintel_top if abs(x) < pj + 0.3 else 0.0
        parts.append(box(x - 0.14, x + 0.14, y0, y1, zb, zt))
        x += 2.0
    for z in (6.0, 12.0, 18.0, 24.0, 30.0, 36.0, 41.0, 46.0, 49.5):
        xe = arch_x_at(z, fw, fh) - 0.1
        if xe > 1:
            parts.append(box(-xe, xe, y0, y1, z - 0.12, z + 0.12))
    xe2 = arch_x_at(lintel_top, fw, fh) - 0.1
    parts.append(box(-xe2, xe2, y0, y1, lintel_top - 0.06, lintel_top + 0.12))
    # solid sill band at the foot of the glazing (outside the portal)
    for sgn in (-1, 1):
        a, bb = (pj, fw / 2 - 0.05)
        x0, x1 = (a, bb) if sgn > 0 else (-bb, -a)
        parts.append(box(x0, x1, y0, y1, 0.0, 0.35))
    v, f = merge(parts)
    return C.make_object("Entry_lobby_mullions", v, f, C.mat("gold"), coll, smooth_shade=False)


def build_arch_rim(coll):
    """Slim gold frame following the pointed glass-arch outline (swept in the facade plane)."""
    fw, fh = P["facade_w"], P["facade_h"]
    pts2 = arch_full(fw - 0.5, fh, 0.0, n=40)
    pts = [(x, P["glass_y"] - 0.18, z) for x, z in pts2]
    n = len(pts)
    v, f = sweep(pts, [0.55] * n, [0.45] * n, up=(0, 1, 0))
    return C.make_object("Entry_glass_arch_rim", v, f, C.mat("gold"), coll, smooth_shade=False)


def build_portal_frame(coll):
    cw = P["portal_w"] / 2 + 0.02        # jamb inner faces at 4.02 -> measured clear 8.04 m
    j = P["jamb"]
    y0, y1 = P["glass_y"] - 0.3, P["glass_y"] + 0.25
    ph = P["portal_h"]
    parts = [box(-cw - j, -cw, y0, y1, 0.0, ph + 0.42), box(cw, cw + j, y0, y1, 0.0, ph + 0.42),
             box(-cw - j, cw + j, y0, y1, ph, ph + 0.42)]
    v, f = merge(parts)
    return C.make_object("Entry_portal_frame", v, f, C.mat("gold"), coll, smooth_shade=False)


def lancet_half():
    return arch_x_at(P["terrace_z"], P["facade_w"], P["facade_h"])


def build_spandrels(coll):
    """Ivory corner panels between the glass arch and the bay edge, up to the +36 terrace."""
    fw, fh = P["facade_w"], P["facade_h"]
    hw = P["bay_hw"]
    tz = 54.0
    xl = 0.0
    parts = []
    for sgn in (1, -1):
        xs = [xl + (hw - xl) * (i / 40.0) ** 1.3 for i in range(41)]
        if sgn < 0:
            xs = [-x for x in reversed(xs)]
        lo = lambda x: min(arch_z(x, fw, fh) - 0.02, tz - 0.1)
        parts.append(prism_columns(xs, lo, lambda x: max(lo(x) + 0.5, min(tz, arch_z(x, fw + 7.0, fh + 2.0))), P["glass_y"] - 0.35, P["glass_y"] + 0.25))
    v, f = merge(parts)
    return C.make_object("Entry_facade_spandrels", v, f, C.mat("ivory"), coll, smooth_shade=False)


def build_vault(coll):
    """Ivory arched shell over the upper glass lancet (arch profile extruded back to the lobby back wall)."""
    fw, fh = P["facade_w"], P["facade_h"]
    xl = lancet_half() - 0.02
    xs = [-xl + 2 * xl * i / 40.0 for i in range(41)]
    v, f = prism_columns(xs, lambda x: arch_z(x, fw, fh) + 0.02, lambda x: arch_z(x, fw, fh) + 0.95,
                         P["glass_y"] - 0.35, P["back_y"])
    return C.make_object("Entry_lobby_vault", v, f, C.mat("ivory"), coll, smooth_shade=False)


def build_lobby_shell(coll):
    hw = P["bay_hw"]
    by = P["back_y"]
    gy = P["glass_y"]
    tz = P["terrace_z"]
    out = []
    # back wall (solid, real): stone to +36, amber tier-3 glazing above (matches podium tier-3 glass)
    v, f = box(-hw, hw, by, by + 0.6, 0.0, tz)
    out.append(C.make_object("Entry_lobby_back_wall", v, f, C.mat("stone"), coll, smooth_shade=False))
    xs = [-hw + 2 * hw * i / 44.0 for i in range(45)]
    v, f = prism_columns(xs, lambda x: tz - 0.01, lambda x: max(tz + 0.05, min(arch_z(x, P["facade_w"], P["facade_h"]) + 0.3, 53.8)), by, by + 0.6)
    out.append(C.make_object("Entry_lobby_back_upper", v, f, C.mat("amber"), coll, smooth_shade=False))
    v, f = merge([box(-hw, -hw + 0.4, gy, by + 0.6, 0.0, tz), box(hw - 0.4, hw, gy, by + 0.6, 0.0, tz)])
    out.append(C.make_object("Entry_lobby_side_walls", v, f, C.mat("stone"), coll, smooth_shade=False))
    # warm glowing arched panel on the back wall (reads through the glass like the references)
    pts = arch_full(40.0, 50.0, 0.0, n=22)
    n = len(pts)
    yv = by - 0.05
    v = [(x, yv, z + 0.4) for x, z in pts]
    f = [tuple(range(n - 1, -1, -1))]      # normal faces -Y (toward the viewer)
    out.append(C.make_object("Entry_lobby_back_glow", v, f, C.mat("amber"), coll, smooth_shade=False, recalc=False))
    return out


def build_forecourt(coll):
    hw = P["bay_hw"]
    by = P["back_y"]
    poly = [(-hw, by), (hw, by), (hw, P["arch_y"]), (32.0, -52.5), (32.0, -59.0), (-32.0, -59.0), (-32.0, -52.5), (-hw, P["arch_y"])]
    v, f = prism(poly, -0.05, 0.12)
    return C.make_object("Entry_forecourt_paving", v, f, C.mat("stone"), coll, smooth_shade=False)


def roof_front_y(x):
    return -50.2 + 2.2 * (x / 22.0) ** 2


def build_roof(coll):
    """+36 terrace apron in front of the upper lancet (carries the dome), with glass parapet at the corners."""
    hw = P["bay_hw"]
    tz, rt = P["terrace_z"], P["apron_t"]
    front = [(x, roof_front_y(x)) for x in [-hw + i * (2 * hw / 22) for i in range(23)]]
    poly = front + [(hw, P["apron_back_y"]), (-hw, P["apron_back_y"])]
    v, f = prism(poly, tz - rt, tz)
    ob = C.make_object("Entry_lobby_roof", v, f, C.mat("ivory"), coll, smooth_shade=False)
    parts_g, parts_r = [], []
    for lo, hi in ((-hw, -15.0), (15.0, hw)):
        xs = [lo + i * (hi - lo) / 8 for i in range(9)]
        top = tz + 1.1
        vv = []
        for x in xs:
            y = roof_front_y(x) + 0.25
            vv += [(x, y, tz), (x, y, top)]
        ff = [(2 * i, 2 * i + 2, 2 * i + 3, 2 * i + 1) for i in range(len(xs) - 1)]
        parts_g.append((vv, ff))
        rings = [[(x, roof_front_y(x) + 0.25 + dy, top + dz) for dy, dz in ((0.1, 0.06), (-0.1, 0.06), (-0.1, -0.06), (0.1, -0.06))] for x in xs]
        parts_r.append(C.loft(rings))
    v, f = merge(parts_g)
    g = C.make_object("Entry_roof_parapet", v, f, C.mat("parapet"), coll, smooth_shade=False)
    v, f = merge(parts_r)
    r = C.make_object("Entry_roof_rail", v, f, C.mat("gold"), coll, smooth_shade=False)
    return [ob, g, r]


def build_canopy(coll):
    y0 = P["glass_y"] - 0.05
    L = 3.4
    hwid = 5.5
    rings = []
    N = 10
    for i in range(N + 1):
        d = L * i / N
        z = 6.4 - 1.1 * (d / L) ** 2
        y = y0 - d
        rings.append([(-hwid, y, z + 0.06), (hwid, y, z + 0.06), (hwid, y, z - 0.06), (-hwid, y, z - 0.06)])
    v, f = C.loft(rings)
    g = C.make_object("Entry_canopy_glass", v, f, C.mat("glass"), coll, smooth_shade=False)
    zf = 6.4 - 1.1
    parts = [box(-hwid - 0.15, hwid + 0.15, y0 - L - 0.2, y0 - L + 0.1, zf - 0.28, zf + 0.12),
             box(-hwid - 0.15, -hwid + 0.05, y0 - L, y0 + 0.05, 5.0, 6.5), box(hwid - 0.05, hwid + 0.15, y0 - L, y0 + 0.05, 5.0, 6.5)]
    for sx in (-hwid + 0.4, hwid - 0.4):
        parts.append(box(sx - 0.05, sx + 0.05, y0 - L + 0.05, y0 - 0.05, zf + 0.12, zf + 0.2))
    v, f = merge(parts)
    fr = C.make_object("Entry_canopy_frame", v, f, C.mat("gold"), coll, smooth_shade=False)
    return [g, fr]


def blade_path(sign, N=44):
    """Right (sign=+1) / left (-1) grand-arch blade centreline: foot -> apex, steep pointed arch in the front view."""
    fx, fy = P["blade_foot"]
    az, ay = P["blade_apex_z"], P["blade_apex_y"]
    P0, P1, P2, P3 = (fx, 0.0), (fx - 2.0, 17.0), (16.0, az - 7.0), (0.0, az)
    pts, ws, ts = [], [], []
    for i in range(N + 1):
        t = i / N
        x, z = C.bezier(P0, P1, P2, P3, t)
        y = fy + (ay - fy) * math.sin(math.pi / 2 * min(1.0, t / 0.55))   # planar arch in front of the glass above the basins
        pts.append((sign * x, y, z))
        ws.append(C.lerp(P["blade_depth"][0], P["blade_depth"][1], t))
        ts.append(C.lerp(P["blade_vis"][0], P["blade_vis"][1], t ** 0.8))
    return pts, ws, ts


def sweep_clipped(path, widths, thicks, z0=None, x1=None):
    """Chamfered section swept along path; first ring clipped (along the tangent) to the plane z=z0, last ring to x=x1."""
    rings = []
    up = Vector((0, 0, 1))
    n = len(path)
    for i, p in enumerate(path):
        tan = (Vector(path[min(i + 1, n - 1)]) - Vector(path[max(i - 1, 0)])).normalized()
        side = tan.cross(up)
        side.normalize()
        nor = side.cross(tan).normalized()
        c = Vector(p)
        hw, ht = widths[i] / 2, thicks[i] / 2
        ring = [c + side * hw * a + nor * ht * b for a, b in _SEC]
        if i == 0 and z0 is not None:
            ring = [v + tan * ((z0 - v.z) / tan.z) for v in ring]
        if i == n - 1 and x1 is not None:
            ring = [v + tan * ((x1 - v.x) / tan.x) for v in ring]
        rings.append([tuple(v) for v in ring])
    return C.loft(rings)


def build_blades(coll):
    out = []
    for sign, side in ((-1, "L"), (1, "R")):
        pts, ws, ts = blade_path(sign)
        v, f = sweep_clipped(pts, ws, ts, z0=0.15, x1=0.0)
        out.append(C.make_object(f"Entry_arch_blade_{side}", v, f, C.mat("ivory"), coll, smooth_shade=False))
    return out


def build_dome(coll):
    cx, cy = P["dome_c"]
    zb = P["dome_z"]
    Rd, H = P["dome_r"], P["dome_h"]
    rd = Rd + 0.75
    # base drum (ivory), stepped, with a plinth reaching down onto the arch extrados
    drum = merge([C.loft([ellipse_pts(cx, cy, rd - 1.0, rd - 1.0, zb - 2.0, 40), ellipse_pts(cx, cy, rd, rd, zb, 40)]),
                  C.loft([ellipse_pts(cx, cy, rd, rd, zb, 40), ellipse_pts(cx, cy, rd, rd, zb + 0.5, 40)]),
                  C.loft([ellipse_pts(cx, cy, rd - 0.4, rd - 0.4, zb + 0.5, 40), ellipse_pts(cx, cy, rd - 0.4, rd - 0.4, zb + 0.9, 40)])])
    d = C.make_object("Entry_dome_base", drum[0], drum[1], C.mat("ivory"), coll, smooth_shade=False)
    zb2 = zb + 0.9
    rings = []
    K = 10
    for k in range(K + 1):
        ph = math.radians(90 - 86 * k / K)
        r = Rd * math.cos(ph)
        z = zb2 + H * math.sin(ph)
        rings.append([(cx + r * math.cos(2 * math.pi * i / 32), cy + r * math.sin(2 * math.pi * i / 32), z) for i in range(32)])
    v, f = C.loft(rings, cap_bottom=False, cap_top=True)
    g = C.make_object("Entry_dome_glass", v, f, C.mat("glass"), coll, smooth_shade=True)
    parts = []
    for m in range(16):
        th = 2 * math.pi * m / 16
        path = []
        for j in range(12):
            ph = math.radians(88 - 80 * j / 11)
            rr = (Rd + 0.12) * math.cos(ph)
            path.append((cx + rr * math.cos(th), cy + rr * math.sin(th), zb2 + (H + 0.12) * math.sin(ph)))
        parts.append(C.blade(path, [0.45] * 12, [0.4] * 12, up=(math.cos(th), math.sin(th), 0)))
    for ph_deg, wd in ((18, 0.4), (50, 0.4)):
        ph = math.radians(ph_deg)
        rr = (Rd + 0.12) * math.cos(ph)
        zz = zb2 + (H + 0.12) * math.sin(ph)
        circ = [(cx + rr * math.cos(2 * math.pi * i / 40), cy + rr * math.sin(2 * math.pi * i / 40), zz) for i in range(41)]
        parts.append(C.blade(circ, [wd] * 41, [0.3] * 41, cap=False))
    rb = merge(parts)
    ribs = C.make_object("Entry_dome_ribs", rb[0], rb[1], C.mat("ivory"), coll, smooth_shade=False)
    fin = merge([C.loft([ellipse_pts(cx, cy, 0.5, 0.5, zb2 + H - 0.1, 12), ellipse_pts(cx, cy, 0.3, 0.3, zb2 + H + 0.6, 12), ellipse_pts(cx, cy, 0.06, 0.06, zb2 + H + 1.4, 12)])])
    fi = C.make_object("Entry_dome_finial", fin[0], fin[1], C.mat("gold"), coll, smooth_shade=False)
    return [d, g, ribs, fi]


def build_basins(coll):
    out = []
    aw, bw = P["basin_a"], P["basin_b"]
    n = 72
    # thick curved ivory collar (D04): profile (outward offset d from the water edge, z)
    prof = [(0.0, 0.12), (0.0, 0.9), (0.14, 1.1), (0.55, 1.22), (1.35, 1.22), (1.8, 1.1), (2.0, 0.9), (2.0, 0.3), (2.9, 0.3), (2.9, -0.05)]
    for side, (cx, cy) in zip(("L", "R"), P["basin_c"]):
        ring = lambda d, z: ellipse_pts(cx, cy, aw + d, bw + d, z, n)
        collar = C.loft([ring(d, z) for d, z in prof], cap_bottom=False, cap_top=False)
        floor = ([(cx, cy, 0.12)] + [(p[0], p[1], 0.12) for p in ring(0.0, 0.12)], [(0, i + 1, (i + 1) % n + 1) for i in range(n)])
        v, f = merge([collar, floor])
        out.append(C.make_object(f"Entry_basin_rim_{side}", v, f, C.mat("ivory"), coll, smooth_shade=False))
        wv = ellipse_pts(cx, cy, aw - 0.1, bw - 0.1, 0.5, n)
        v = [(cx, cy, 0.5)] + wv
        f = [(0, i + 1, (i + 1) % n + 1) for i in range(n)]
        out.append(C.make_object(f"Entry_basin_water_{side}", v, f, C.mat("water"), coll, smooth_shade=False))
        inlay = C.loft([ring(0.88, 1.235), ring(1.02, 1.235)], cap_bottom=False, cap_top=False)
        out.append(C.make_object(f"Entry_basin_inlay_{side}", inlay[0], inlay[1], C.mat("gold"), coll, smooth_shade=False))
    return out


# ---------------------------------------------------------------- verification --------------------
def _cast(x, z, y0=-100.0):
    sc = bpy.context.scene
    deps = bpy.context.evaluated_depsgraph_get()
    ok, loc, nor, idx, ob, mw = sc.ray_cast(deps, Vector((x, y0, z)), Vector((0, 1, 0)))
    return (loc.y, ob.name) if ok else (None, None)


def verify_opening():
    """Rays along +Y at z=1.0 / 1.7 m, x in [-4,4], from y=-100: the first hit must be the lobby back wall (or
    its glow panel); nothing (arch band, porch, glazing, portal frame, canopy, blades) may stand in the way."""
    bpy.context.view_layer.update()
    res = {"rays": [], "pass": True}
    allowed = ("Entry_lobby_back",)
    for z in (1.0, 1.7):
        for i in range(9):
            x = -4.0 + i
            y, name = _cast(x, z)
            good = bool(name) and name.startswith(allowed)
            res["rays"].append({"x": x, "z": z, "hit_y": None if y is None else round(y, 3), "obj": name, "ok": good})
            res["pass"] = res["pass"] and good
    # measured clearances by scanning (first hit must be the lobby back wall to count as free)
    def free(x, z):
        y, name = _cast(x, z)
        return bool(name) and name.startswith(allowed)

    def scan(lo, hi, step, test):
        """Largest v (stepping up from lo) such that test holds for all values up to it (first failure ends)."""
        v = lo
        last = None
        while v <= hi + 1e-9:
            if not test(v):
                break
            last = v
            v += step
        return None if last is None else round(last, 3)
    res["portal_clear_halfwidth_m"] = scan(0.0, 12.0, 0.01, lambda x: free(x, 2.0))
    res["portal_clear_height_m"] = scan(0.2, 9.0, 0.01, lambda z: free(0.0, z))

    def band_free(x, z):
        y, name = _cast(x, z)
        return name != "Entry_arch_band"
    res["arch_clear_halfwidth_m"] = scan(0.0, 14.0, 0.01, lambda x: band_free(x, 0.5))
    res["arch_clear_height_m"] = scan(0.5, 20.0, 0.01, lambda z: band_free(0.0, z))
    _last_verify.clear()
    _last_verify.update(res)
    return res


def _out_dir():
    a = sys.argv
    if "--out" in a:
        return a[a.index("--out") + 1]
    return None


# ---------------------------------------------------------------- build ---------------------------
def build():
    coll = C.collection(COLLECTION)
    build_forecourt(coll)
    build_arch_porch(coll)
    build_glazing(coll)
    build_mullions(coll)
    build_arch_rim(coll)
    build_portal_frame(coll)
    build_spandrels(coll)
    pass  # vault replaced by full-height spandrels
    build_lobby_shell(coll)
    build_roof(coll)
    build_canopy(coll)
    build_blades(coll)
    build_dome(coll)
    build_basins(coll)
    try:
        res = verify_opening()
        od = _out_dir()
        if od:
            os.makedirs(od, exist_ok=True)
            with open(os.path.join(od, "entrance_verify.json"), "w") as fh:
                json.dump(res, fh, indent=1)
        print("ENTRANCE_VERIFY pass=%s portal_w/2=%s portal_h=%s arch_w/2=%s arch_h=%s" % (
            res["pass"], res.get("portal_clear_halfwidth_m"), res.get("portal_clear_height_m"),
            res.get("arch_clear_halfwidth_m"), res.get("arch_clear_height_m")))
    except Exception as e:  # never let the check break the build
        print("ENTRANCE_VERIFY_ERROR", repr(e))
