"""Crown Landmark podium (round 3): foundation + plinth steps, three stepped terraces, sculpted fascia slabs,
tulip-pier arcades with mixed round/ogive arches, gold mullions, amber glazing, blue glass parapets, terrace detail.

Frame: metres, Z up, front = -Y, X = right, origin = tower centre at ground.
Per tier t (floor z0, slab top zt = z0 + 18):
  Podium_Slab_Tn      slab with sculpted fascia: 1.9-2.6 m deep bullnose lip whose cove soffit rises into the slab (the
                      lip is deepest over the piers and curves up between them); top z and plan footprint exactly as R06
  Podium_Piers_Tn     arcade skin: tulip piers + lintel, arches of varying width/shape; THIN HOLLOW SHELL (0.5 m skin, open back)
  Podium_Glazing_Tn   recessed amber glazed wall behind the arcade (thin shell)
  Podium_Mullions_Tn  gold mullions, transoms and arch tracery on every opening
  Podium_Parapet_Tn   blue glass parapet band at the slab edge; Podium_Coping_Tn ivory kerb + coping
  Podium_Terrace_Tn   channel kerbs, paving lines, stepped corner pads (stone);  Podium_Water_Tn  shallow water channel
Foundation: Podium_Foundation (160 x 120, top 0, bottom -1.2) + Podium_Plinth (two edge steps, open at the entry).
The front centre bay |x| <= GAP_HALF has no wall/piers/parapet on any tier (entrance module supplies roof + spandrels).
Round 3: for |x| > GAP_HALF the front slab edge / arcade of every tier is set back (EDGE_F) so the rib-foot basins and
arch-blade feet stand free in front of the podium; arcade bays that would touch a rib are cut out cleanly (pockets) and
parapet / coping stop at the rib; corner fascia is deeper (curved corner overhang) and the piers flare harder.
"""
import math
import bisect
import bpy
import bmesh
from mathutils import Vector, geometry
import cl_common as C

COLLECTION = "Podium"

# ---------------------------------------------------------------- parameters --------------------------------------
GAP_HALF = 22.0           # front centre bay half width kept open (no wall, no piers)
TIER_H = 18.0             # floor to slab top
WALL_INSET = 5.4          # slab edge -> glazed wall line (plan offset)
SLAB_R = 16.0             # slab corner radius (wall-line radius = SLAB_R - WALL_INSET)
FOUND_R = 12.0
# front slab edge (plan y) for |x| > GAP_HALF, and in the centre tongue |x| <= GAP_HALF, per tier
EDGE_F = {1: -31.0, 2: -29.0, 3: -28.0}
EDGE_L = {1: -31.0, 2: -39.6, 3: -32.6}
D_CORNER = 4.2            # deeper fascia over the curved corner bays (corner overhang)
POCKET_PAD = 1.6          # clearance along the wall between a rib footprint and the cut arcade end
# fascia / slab
D_PIER, D_MID, D_NOTCH = 3.0, 2.3, 1.7   # fascia depth below the slab top: over piers / mid-bay / at the entry notch
T_IN = 1.5                # slab thickness inside the fascia zone
W_SOFFIT, W_CAP, R_BULL = 3.6, 6.5, 0.55
# arcade
PIER_W = 4.4              # nominal pier width at the floor (bay - open)
OPEN_MAX = 14.6
PIER_OUT0, PIER_OUT1, PIER_P = 2.4, 5.1, 1.6   # pier face offset: at floor, at top, flare exponent (tulip)
ARCH_EXP = 2.3            # superellipse exponent for the round arches
SKIN_T = 0.5              # hollow pier skin thickness
SPRING = {1: 8.4, 2: 8.2, 3: 8.0}
CROWN_ROUND = {1: 15.4, 2: 15.0, 3: 14.6}
CROWN_OGIVE = {1: 15.9, 2: 15.5, 3: 15.1}
# parapet / terrace
PARAPET_IN, PARAPET_T = 0.55, 0.14
KERB_W, KERB_H = 0.76, 0.28
GLASS_H = 1.30            # glass band above the kerb
COPING = (0.52, 0.18)
GLASS_OFF = (-0.35, -0.45)
CH_OUT, CH_IN = 4.4, 2.25  # channel edges as offset from the wall line (outward positive); slab edge = WALL_INSET
MAX_IN = {1: 6.2, 2: 5.2, 3: 4.6}   # free terrace depth (from wall line) usable by paving lines


# ---------------------------------------------------------------- 2D helpers --------------------------------------
def _arc(cx, cy, r, a0, a1, n):
    return [(cx + r * math.cos(math.radians(a0 + (a1 - a0) * i / n)),
             cy + r * math.sin(math.radians(a0 + (a1 - a0) * i / n))) for i in range(n + 1)]


def _dedupe(pts, tol=1e-6):
    out = []
    for p in pts:
        if not out or abs(p[0] - out[-1][0]) > tol or abs(p[1] - out[-1][1]) > tol:
            out.append(p)
    if len(out) > 1 and abs(out[0][0] - out[-1][0]) < tol and abs(out[0][1] - out[-1][1]) < tol:
        out.pop()
    return out


def outline(w, d, r, notch=0.0, n=10):
    """Closed CCW rounded rectangle; optional notch (recess) in the front edge for |x| <= GAP_HALF."""
    W, D = w / 2, d / 2
    pts = _arc(-W + r, -D + r, r, 180, 270, n)
    if notch > 0:
        pts += [(-GAP_HALF, -D), (-GAP_HALF, -D + notch), (GAP_HALF, -D + notch), (GAP_HALF, -D)]
    pts += _arc(W - r, -D + r, r, -90, 0, n)
    pts += _arc(W - r, D - r, r, 0, 90, n)
    pts += _arc(-W + r, D - r, r, 90, 180, n)
    return _dedupe(pts)


def offset_poly(pts, o):
    """Mitre offset of a closed CCW polygon: o > 0 outward, o < 0 inward."""
    n = len(pts)
    out = []
    for i in range(n):
        p0, p1, p2 = pts[i - 1], pts[i], pts[(i + 1) % n]
        e1 = (p1[0] - p0[0], p1[1] - p0[1])
        e2 = (p2[0] - p1[0], p2[1] - p1[1])
        l1, l2 = math.hypot(*e1), math.hypot(*e2)
        n1 = (e1[1] / l1, -e1[0] / l1)
        n2 = (e2[1] / l2, -e2[0] / l2)
        dd = max(1.0 + n1[0] * n2[0] + n1[1] * n2[1], 1e-3)
        out.append((p1[0] + (n1[0] + n2[0]) / dd * o, p1[1] + (n1[1] + n2[1]) / dd * o))
    return out


def run_path(w, d, r, step=0.45, gap=GAP_HALF, y0=0.0):
    """Open dense path along the wall line from front x=+gap, CCW around, to front x=-gap."""
    W, D = w / 2, d / 2
    na = max(8, int(math.ceil(math.pi / 2 * r / step)))
    pts = []

    def seg(a, b):
        L = math.hypot(b[0] - a[0], b[1] - a[1])
        k = max(1, int(math.ceil(L / step)))
        return [(a[0] + (b[0] - a[0]) * i / k, a[1] + (b[1] - a[1]) * i / k) for i in range(k)]

    pts += seg((gap, -D), (W - r, -D))
    pts += _arc(W - r, -D + r, r, -90, 0, na)[:-1]
    pts += seg((W, -D + r), (W, D - r))
    pts += _arc(W - r, D - r, r, 0, 90, na)[:-1]
    pts += seg((W - r, D), (-W + r, D))
    pts += _arc(-W + r, D - r, r, 90, 180, na)[:-1]
    pts += seg((-W, D - r), (-W, -D + r))
    pts += _arc(-W + r, -D + r, r, 180, 270, na)[:-1]
    pts += seg((-W + r, -D), (-gap, -D))
    pts.append((-gap, -D))
    return _dedupe([(x, y + y0) for x, y in pts])


class Path:
    """Arc-length parametrised open polyline with outward (right-hand, CCW) normals."""

    def __init__(self, pts):
        self.p = pts
        self.s = [0.0]
        for a, b in zip(pts[:-1], pts[1:]):
            self.s.append(self.s[-1] + math.hypot(b[0] - a[0], b[1] - a[1]))
        self.L = self.s[-1]
        nv = []
        for i in range(len(pts)):
            a = pts[max(i - 1, 0)]
            b = pts[min(i + 1, len(pts) - 1)]
            tx, ty = b[0] - a[0], b[1] - a[1]
            l = math.hypot(tx, ty)
            nv.append((ty / l, -tx / l))
        self.n = nv

    def at(self, s):
        s = min(max(s, 0.0), self.L)
        i = min(max(bisect.bisect_right(self.s, s) - 1, 0), len(self.p) - 2)
        t = (s - self.s[i]) / max(self.s[i + 1] - self.s[i], 1e-9)
        p = (self.p[i][0] + (self.p[i + 1][0] - self.p[i][0]) * t, self.p[i][1] + (self.p[i + 1][1] - self.p[i][1]) * t)
        nx = self.n[i][0] + (self.n[i + 1][0] - self.n[i][0]) * t
        ny = self.n[i][1] + (self.n[i + 1][1] - self.n[i][1]) * t
        l = math.hypot(nx, ny)
        return p, (nx / l, ny / l)


# ---------------------------------------------------------------- mesh helpers ------------------------------------
def weld(verts, faces, tol=2e-3):
    key, remap, nv = {}, [], []
    for v in verts:
        k = (round(v[0] / tol), round(v[1] / tol), round(v[2] / tol))
        if k not in key:
            key[k] = len(nv)
            nv.append(v)
        remap.append(key[k])
    nf = []
    for f in faces:
        g = []
        for i in f:
            j = remap[i]
            if not g or g[-1] != j:
                g.append(j)
        if len(g) > 1 and g[0] == g[-1]:
            g.pop()
        if len(g) >= 3 and len(set(g)) == len(g):
            nf.append(tuple(g))
    return nv, nf


def cap_faces(ring_idx, verts, up=None):
    """Triangulate a ring; with up=True/False orient every triangle to face +Z/-Z (zero-area slivers kept so the rim stays closed)."""
    pts = [Vector(verts[i]) for i in ring_idx]
    tris = geometry.tessellate_polygon([pts])
    out = []
    for a, b, c in tris:
        t = (ring_idx[a], ring_idx[b], ring_idx[c])
        if up is not None:
            pa, pb, pc = pts[a], pts[b], pts[c]
            nz = (pb.x - pa.x) * (pc.y - pa.y) - (pb.y - pa.y) * (pc.x - pa.x)
            if abs(nz) > 1e-9 and (nz > 0) != up:
                t = (t[0], t[2], t[1])
        out.append(t)
    return out


def join(*vfs):
    V, F = [], []
    for v, f in vfs:
        b = len(V)
        V += list(v)
        F += [tuple(i + b for i in fc) for fc in f]
    return V, F


def slab_mesh(poly, zt, w_taper, t0, t1):
    """Plain thin slab (used for the foundation)."""
    prof = [(w_taper, 0.0), (0.0, 0.0), (0.0, -t0)]
    prof += [(w_taper * f, -(t0 + (t1 - t0) * C.smooth(f))) for f in (0.15, 0.3, 0.5, 0.75, 1.0)]
    verts, faces, rings = [], [], []
    for o, dz in prof:
        rp = offset_poly(poly, -o) if o > 0 else poly
        rings.append(list(range(len(verts), len(verts) + len(rp))))
        verts += [(x, y, zt + dz) for x, y in rp]
    n = len(poly)
    for k in range(len(rings) - 1):
        for i in range(n):
            j = (i + 1) % n
            faces.append((rings[k][i], rings[k][j], rings[k + 1][j], rings[k + 1][i]))
    faces += cap_faces(rings[0], verts)
    faces += cap_faces(rings[-1], verts)
    return verts, faces


def closed_tube(poly, zbase, section):
    verts, rings = [], []
    for off, dz in section:
        rp = offset_poly(poly, off)
        rings.append(list(range(len(verts), len(verts) + len(rp))))
        verts += [(x, y, zbase + dz) for x, y in rp]
    faces = []
    n = len(poly)
    m = len(section)
    for a in range(m):
        b = (a + 1) % m
        for i in range(n):
            j = (i + 1) % n
            faces.append((rings[a][i], rings[a][j], rings[b][j], rings[b][i]))
    return verts, faces


def open_tube(path, zbase, section, caps=True):
    verts, rings = [], []
    n = len(path.p)
    for i in range(n):
        nx, ny = path.n[i]
        px, py = path.p[i]
        rings.append(list(range(len(verts), len(verts) + len(section))))
        verts += [(px + nx * off, py + ny * off, zbase + dz) for off, dz in section]
    faces = []
    m = len(section)
    for i in range(n - 1):
        for a in range(m):
            b = (a + 1) % m
            faces.append((rings[i][a], rings[i][b], rings[i + 1][b], rings[i + 1][a]))
    if caps:
        faces.append(tuple(rings[0]))
        faces.append(tuple(reversed(rings[-1])))
    return verts, faces


def strip(path, zbase, off0, off1, h, i0=0, i1=None):
    """Rectangular band (offsets off0..off1 from the path, height h) along path[i0:i1+1]."""
    sub = Path(path.p[i0:(i1 + 1) if i1 is not None else None]) if (i0 or i1 is not None) else path
    return open_tube(sub, zbase, [(off0, 0.0), (off1, 0.0), (off1, h), (off0, h)])


def box_at(path, s, o0, o1, w, zbase, h):
    """Small box across the path at arc length s, spanning offsets o0..o1, width w along the path."""
    p, n = path.at(s)
    t = (-n[1], n[0])
    v = []
    for dz in (0.0, h):
        for (a, off) in ((-w / 2, o0), (-w / 2, o1), (w / 2, o1), (w / 2, o0)):
            v.append((p[0] + n[0] * off + t[0] * a, p[1] + n[1] * off + t[1] * a, zbase + dz))
    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 coarse(path, forced=(), ang=6.0):
    """Simplified copy of a dense path: keeps a vertex whenever the normal has turned `ang` degrees since the last
    kept one (straights collapse to their end points) plus `forced` indices. Returns (Path, {fine idx: coarse idx})."""
    keep = [0]
    last = path.n[0]
    cs = math.cos(math.radians(ang))
    fs = set(forced)
    for i in range(1, len(path.p) - 1):
        n = path.n[i]
        nxt = path.n[i + 1]
        turn = n[0] * last[0] + n[1] * last[1] < cs
        edge = (n[0] * nxt[0] + n[1] * nxt[1]) < 0.9999 and (n[0] * last[0] + n[1] * last[1]) > 0.9999
        if turn or i in fs or edge:
            keep.append(i)
            last = n
    keep.append(len(path.p) - 1)
    return Path([path.p[i] for i in keep]), {i: k for k, i in enumerate(keep)}


def orient_solids(verts, faces):
    """Flip every connected component whose signed volume is negative (so all closed solids face outward)."""
    par = list(range(len(verts)))

    def find(a):
        while par[a] != a:
            par[a] = par[par[a]]
            a = par[a]
        return a

    for f in faces:
        for i in f[1:]:
            ra, rb = find(f[0]), find(i)
            if ra != rb:
                par[ra] = rb
    vol = {}
    for f in faces:
        r = find(f[0])
        a = Vector(verts[f[0]])
        for k in range(1, len(f) - 1):
            vol[r] = vol.get(r, 0.0) + a.dot(Vector(verts[f[k]]).cross(Vector(verts[f[k + 1]]))) / 6.0
    return verts, [tuple(reversed(f)) if vol[find(f[0])] < 0 else tuple(f) for f in faces]


def shade(ob, angle=38.0):
    """Smooth faces, keep creases sharper than `angle` degrees."""
    me = ob.data
    bm = bmesh.new()
    bm.from_mesh(me)
    for f in bm.faces:
        f.smooth = f.calc_area() > 1e-4      # zero-area slivers stay flat so they cannot poison vertex normals
    lim = math.radians(angle)
    for e in bm.edges:
        if len(e.link_faces) == 2 and e.calc_face_angle(0.0) > lim:
            e.smooth = False
    bm.to_mesh(me)
    bm.free()


# ---------------------------------------------------------------- layout --------------------------------------------
def _weights(n, pos, tier):
    if n == 1:
        return [1.0]
    if pos == "first":      # nearest the entry first: larger bays by the centre, narrower toward the corner
        w = [1.08 - 0.16 * i / (n - 1) for i in range(n)]
    elif pos == "last":
        w = [0.92 + 0.16 * i / (n - 1) for i in range(n)]
    else:                   # long sides: larger central bays, narrower near the corners
        w = [0.92 + 0.24 * math.sin(math.pi * (i + 0.5) / n) ** 2 for i in range(n)]
    s = sum(w)
    return [x * n / s for x in w]


# measured rib plan footprints (z, x0, x1, y0, y1) at height z, left-hand ribs R1 (front), R3 (side), R5 (rear);
# right-hand ribs mirror x.  Source: round-3 assembly slices (+-2 m); re-measure if ribs.py changes.
_RIBF = {
    "R1": [(2, -71.0, -44.8, -43.6, -35.5), (10, -69.5, -46.1, -42.0, -34.4), (18, -68.1, -47.8, -40.3, -33.3),
           (27, -66.2, -48.8, -38.1, -31.9), (36, -64.8, -49.2, -36.5, -30.5), (45, -62.7, -48.7, -34.5, -29.2),
           (54, -60.9, -47.1, -33.0, -27.5), (62, -58.1, -45.5, -31.0, -26.1)],
    "R3": [(2, -66.7, -60.2, -4.1, 16.1), (10, -65.0, -58.9, -2.8, 14.8), (18, -63.3, -57.2, -1.6, 13.5),
           (27, -61.0, -56.0, -0.6, 12.5), (36, -59.3, -54.3, 0.0, 11.9), (45, -57.0, -52.2, 0.4, 11.4),
           (54, -54.6, -50.5, 0.7, 11.2), (62, -52.5, -47.8, 0.8, 11.0)],
    "R5": [(2, -52.1, -29.0, 40.0, 47.0), (10, -52.4, -32.2, 38.7, 45.4), (18, -52.9, -35.6, 37.0, 43.7),
           (27, -53.2, -38.3, 35.8, 41.4), (36, -53.6, -40.0, 34.1, 39.7), (45, -53.9, -41.4, 32.3, 37.6),
           (54, -54.0, -41.9, 30.9, 35.5), (62, -53.3, -40.9, 29.0, 34.0)],
}


def rib_boxes(z):
    """Plan boxes (x0, x1, y0, y1) of the six ribs at height z (interpolated)."""
    out = []
    for key, rows in _RIBF.items():
        zz = min(max(z, rows[0][0]), rows[-1][0])
        i = 0
        while i < len(rows) - 2 and zz > rows[i + 1][0]:
            i += 1
        r0, r1 = rows[i], rows[i + 1]
        t = (zz - r0[0]) / (r1[0] - r0[0])
        x0, x1, y0, y1 = [r0[k] + (r1[k] - r0[k]) * t for k in (1, 2, 3, 4)]
        out.append((x0, x1, y0, y1))
        out.append((-x1, -x0, y0, y1))
    return out


def rib_hit(x, y, z, pad):
    for x0, x1, y0, y1 in rib_boxes(z):
        if x0 - pad <= x <= x1 + pad and y0 - pad <= y <= y1 + pad:
            return True
    return False


def wall_hits(path, z0, hs):
    """Per dense path index: does the arcade volume (glazing .. pier face) at this point touch a rib footprint?"""
    hit = []
    zs = [0.5 + k * (hs - 0.5) / 8 for k in range(9)]
    for i, (p, n) in enumerate(zip(path.p, path.n)):
        h = False
        for zl in zs:
            out = pier_out(zl, hs)
            for off in (-0.5, 0.0, out * 0.5, out):
                if rib_hit(p[0] + n[0] * off, p[1] + n[1] * off, z0 + zl, 0.5):
                    h = True
                    break
            if h:
                break
        hit.append(h)
    return hit


def wall_runs(path, z0, hs, min_len=9.0):
    """Index ranges [i0, i1] of the wall path that stay clear of the ribs (pockets padded by POCKET_PAD)."""
    hit = wall_hits(path, z0, hs)
    n = len(hit)
    pad = []
    for i in range(n):
        pad.append(any(hit[j] for j in range(n) if abs(path.s[j] - path.s[i]) <= POCKET_PAD))
    runs, i = [], 0
    while i < n:
        if pad[i]:
            i += 1
            continue
        j = i
        while j + 1 < n and not pad[j + 1]:
            j += 1
        if path.s[j] - path.s[i] >= min_len:
            runs.append((i, j))
        i = j + 1
    return runs


def layout(path, ww, wd, r, tier, y0=0.0, runs=None):
    """Bays along the wall path (list of dicts s0, w, kind, open, corner) for each clear run. Corner = one ogive bay."""
    W, D = ww / 2, wd / 2
    if runs is None:
        runs = [(0, len(path.p) - 1)]
    bays = []
    for ri, (a, b) in enumerate(runs):
        flags = [abs(path.p[i][0]) > W - r + 1e-6 and abs(path.p[i][1] - y0) > D - r + 1e-6 for i in range(a, b + 1)]
        groups = []
        for k, f in enumerate(flags):
            if not groups or groups[-1][0] != f:
                groups.append([f, a + k, a + k])
            groups[-1][2] = a + k
        ng = len(groups)
        for gi, (isc, i0, i1) in enumerate(groups):
            s0 = path.s[i0]
            s1 = path.s[groups[gi + 1][1]] if gi + 1 < ng else path.s[b]
            L = s1 - s0
            if L < 4.6 + 3.0:
                continue
            if isc:
                n, ws, kinds = 1, [1.0], ["ogive"]
                corner = True
            else:
                corner = False
                n = max(1, int(round(L / 16.5)))
                while n > 1 and L / n < 12.0:
                    n -= 1
                first = ri == 0 and gi == 0 and a == 0
                last = ri == len(runs) - 1 and gi == ng - 1 and b == len(path.p) - 1
                pos = "first" if first else ("last" if last else "mid")
                ws = _weights(n, pos, tier)
                kinds = []
                wmax = max(ws)
                for k in range(n):
                    if ws[k] >= wmax - 1e-6 and n > 2:
                        kinds.append("round")
                    else:
                        kinds.append("ogive" if (k + gi + ri + tier) % 2 == 0 else "round")
            mean = L / n
            pos_s = s0
            for k in range(n):
                bw = mean * ws[k]
                op = min(OPEN_MAX, bw - PIER_W)
                bays.append(dict(s0=pos_s, w=bw, kind=kinds[k], open=op, corner=corner))
                pos_s += bw
    return bays


# ---------------------------------------------------------------- arches ---------------------------------------------
def pier_out(zl, hs):
    t = min(max(zl / hs, 0.0), 1.0)
    return PIER_OUT0 + (PIER_OUT1 - PIER_OUT0) * t ** PIER_P


def arch_curve(kind, a, sp, rise, n=18):
    """Left-to-right arch points (x, zl), 2n+1 of them, springing at (+-a, sp), apex (0, sp+rise)."""
    pts = []
    if kind == "ogive":
        half = C.pointed_arch(2 * a, rise, n)          # right half: (a,0) -> (0,rise)
        left = [(-x, sp + z) for x, z in half]
        right = [(x, sp + z) for x, z in reversed(half)][1:]
        pts = left + right
    else:
        N = 2 * n + 1
        e = ARCH_EXP
        for i in range(N):
            ph = math.pi * i / (N - 1)
            c, s_ = math.cos(ph), math.sin(ph)
            pts.append((-a * math.copysign(abs(c) ** (2 / e), c), sp + rise * abs(s_) ** (2 / e)))
    return pts


def arch_z(kind, a, sp, rise, x):
    """Height of the arch intrados at lateral position x."""
    x = abs(x)
    if x >= a:
        return sp
    if kind == "ogive":
        c = (rise ** 2 - a ** 2) / (2 * a)
        R = a + c
        return sp + math.sqrt(max(R * R - (x + c) ** 2, 0.0))
    return sp + rise * max(1 - (x / a) ** ARCH_EXP, 0.0) ** (1 / ARCH_EXP)


def bay_params(b, tier):
    if b["kind"] == "ogive":
        sp, crown = SPRING[tier] - 1.6, CROWN_OGIVE[tier]
    else:
        sp, crown = SPRING[tier], CROWN_ROUND[tier]
    return b["open"] / 2, sp, crown - sp


# ---------------------------------------------------------------- arcade shell ---------------------------------------
def arcade_skin(path, z0, bays, tier, hc, hs):
    """Perforated fascia skin (tulip piers + lintel) as bays along `path`: front skin + reveals only (open back)."""
    verts, faces = [], []
    N1, K = 7, 3
    n_half = 12
    N2 = 2 * n_half + 1
    for b in bays:
        a, sp, rise = bay_params(b, tier)
        w = b["w"]
        sc = b["s0"] + w / 2
        arch = arch_curve(b["kind"], a, sp, rise, n_half)
        inner, outer = [], []
        for i in range(N1):
            inner.append((-a, sp * i / N1))
            outer.append((-w / 2, hc * i / N1))
        for i in range(N2):
            inner.append(arch[i])
            outer.append((-w / 2 + w * i / (N2 - 1), hc))
        for i in range(N1):
            inner.append((a, sp * (N1 - 1 - i) / N1))
            outer.append((w / 2, hc * (N1 - 1 - i) / N1))
        M = len(inner)

        def P(u, zl, off):
            p, n = path.at(sc + u)
            return (p[0] + n[0] * off, p[1] + n[1] * off, z0 + zl)

        fid = []
        for k in range(K + 1):
            t = k / K
            row = []
            for j in range(M):
                u = inner[j][0] + (outer[j][0] - inner[j][0]) * t
                zl = inner[j][1] + (outer[j][1] - inner[j][1]) * t
                row.append(len(verts))
                verts.append(P(u, zl, pier_out(zl, hs)))
            fid.append(row)
        bid = []
        row = []
        for j in range(M):
            row.append(len(verts))
            verts.append(P(inner[j][0], inner[j][1], 0.0))
        bid = row
        for k in range(K):
            for j in range(M - 1):
                faces.append((fid[k][j], fid[k][j + 1], fid[k + 1][j + 1], fid[k + 1][j]))
        for j in range(M - 1):
            faces.append((fid[0][j + 1], fid[0][j], bid[j], bid[j + 1]))      # reveal
    return verts, faces


def hollow_shell(verts, faces, t):
    """Give an open outward-oriented skin a thickness t inward; rim faces close the open edges."""
    vn = [Vector((0, 0, 0)) for _ in verts]
    for f in faces:
        pts = [Vector(verts[i]) for i in f]
        nrm = Vector((0, 0, 0))
        for i in range(len(pts)):
            a, b = pts[i], pts[(i + 1) % len(pts)]
            nrm += Vector(((a.y - b.y) * (a.z + b.z), (a.z - b.z) * (a.x + b.x), (a.x - b.x) * (a.y + b.y)))
        for i in f:
            vn[i] += nrm
    n0 = len(verts)
    nv = list(verts)
    for i, v in enumerate(verts):
        nrm = vn[i]
        if nrm.length > 1e-9:
            nrm = nrm.normalized()
        nv.append(tuple(Vector(v) - nrm * t))
    nf = [tuple(f) for f in faces]
    nf += [tuple(i + n0 for i in reversed(f)) for f in faces]
    edges = {}
    for f in faces:
        for i in range(len(f)):
            a, b = f[i], f[(i + 1) % len(f)]
            edges[(a, b)] = True
    for (a, b) in list(edges):
        if (b, a) not in edges:
            nf.append((b, a, a + n0, b + n0))
    return nv, nf


# ---------------------------------------------------------------- fascia slab ----------------------------------------
def fascia_depth(s, bays):
    starts = [b["s0"] for b in bays]
    k = min(max(bisect.bisect_right(starts, s) - 1, 0), len(bays) - 1)
    b = bays[k]
    tt = min(max((s - b["s0"]) / b["w"], 0.0), 1.0)
    if b["corner"]:       # curved corner overhang: deepest lip over the middle of the corner bay
        return D_PIER + (D_CORNER - D_PIER) * math.sin(math.pi * tt) ** 0.7
    return D_MID + (D_PIER - D_MID) * 0.5 * (1 + math.cos(2 * math.pi * tt))


def slab_dense(path, bays, yl, step_skip=3):
    """Dense slab outline (CCW) following the wall path offset by WALL_INSET; the front tongue |x| <= GAP_HALF closes the
    outline at y = yl (jog legs when yl differs from the slab edge of the path ends). Returns points and depth per vertex."""
    idx = list(range(0, len(path.p), step_skip))
    if idx[-1] != len(path.p) - 1:
        idx.append(len(path.p) - 1)
    pts, dv = [], []
    for i in idx:
        p, n = path.p[i], path.n[i]
        pts.append((p[0] + n[0] * WALL_INSET, p[1] + n[1] * WALL_INSET))
        dv.append(fascia_depth(path.s[i], bays))
    xl, yc = pts[-1]
    xr, _ = pts[0]
    jog = abs(yl - yc) > 1e-6
    if jog:
        k = 8
        for i in range(1, k + 1):             # left leg
            t = i / k
            pts.append((xl, yc + (yl - yc) * t))
            dv.append(D_PIER + (D_NOTCH - D_PIER) * t)
    m = 40
    for i in range(1 if jog else 1, m):
        t = i / m
        pts.append((xl + (xr - xl) * t, yl))
        dv.append(D_NOTCH)
    if jog:
        for i in range(0, k):                 # right leg back to the path start
            t = i / k
            pts.append((xr, yl + (yc - yl) * t))
            dv.append(D_NOTCH + (D_PIER - D_NOTCH) * t)
    op, od = [], []
    for p, d in zip(pts, dv):
        if not op or abs(p[0] - op[-1][0]) > 1e-6 or abs(p[1] - op[-1][1]) > 1e-6:
            op.append(p)
            od.append(d)
    return op, od


def slab_fascia(poly, dv, zt):
    """Closed slab solid: thick sculpted lip (bullnose + cove soffit) following the outline; flat top at zt.
    Returns verts, faces, number of top-cap faces."""
    n = len(poly)
    ob = []      # per-ring (offset, function d -> dz)
    ob.append((W_CAP, lambda d: 0.0))
    ob.append((0.18, lambda d: 0.0))
    ob.append((0.0, lambda d: -0.18))
    ob.append((0.0, lambda d: -(d - R_BULL)))
    for ph in (30.0, 60.0, 90.0):
        c, s_ = math.cos(math.radians(ph)), math.sin(math.radians(ph))
        ob.append((R_BULL * (1 - c), (lambda s_: lambda d: -(d - R_BULL) - R_BULL * s_)(s_)))
    for f in (0.18, 0.4, 0.68, 1.0):
        o = R_BULL + (W_SOFFIT - R_BULL) * f
        ob.append((o, (lambda f: lambda d: -(T_IN + (d - T_IN) * (1 - f) ** 2.2))(f)))
    ob.append((W_CAP, lambda d: -T_IN))
    verts, rings = [], []
    cache = {}
    for o, fn in ob:
        key = round(o, 6)
        if key not in cache:
            cache[key] = offset_poly(poly, -o) if o > 1e-9 else poly
        rp = cache[key]
        rings.append(list(range(len(verts), len(verts) + n)))
        verts += [(x, y, zt + fn(dv[i])) for i, (x, y) in enumerate(rp)]
    # corner-only index list of the flat cap rings (collinear points removed: no sliver triangles in the caps)
    kept = []
    for i in range(n):
        p0, p1, p2 = poly[i - 1], poly[i], poly[(i + 1) % n]
        cr = (p1[0] - p0[0]) * (p2[1] - p1[1]) - (p1[1] - p0[1]) * (p2[0] - p1[0])
        if abs(cr) > 1e-6:
            kept.append(i)
    nk = len(kept)

    def span(a, b):          # dense indices a..b walking forward (cyclic)
        out = [a]
        while out[-1] != b:
            out.append((out[-1] + 1) % n)
        return out

    faces = []
    last = len(rings) - 1
    for k in range(last):
        if k == 0:           # flat top band: sparse ring 0 stitched to dense ring 1 with n-gons
            for q in range(nk):
                a, b = kept[q], kept[(q + 1) % nk]
                sp = span(a, b)
                faces.append(tuple([rings[0][a]] + [rings[1][i] for i in sp] + [rings[0][b]]))
        elif k == last - 1:  # flat underside band: dense ring k stitched to sparse last ring
            for q in range(nk):
                a, b = kept[q], kept[(q + 1) % nk]
                sp = span(a, b)
                faces.append(tuple([rings[k][a], rings[last][a], rings[last][b]] + [rings[k][i] for i in reversed(sp[1:])]))
        else:
            for i in range(n):
                j = (i + 1) % n
                faces.append((rings[k][i], rings[k + 1][i], rings[k + 1][j], rings[k][j]))
    top = cap_faces([rings[0][i] for i in kept], verts, up=True)
    bot = cap_faces([rings[last][i] for i in kept], verts, up=False)
    return verts, faces + top + bot, len(top)


# ---------------------------------------------------------------- mullions -------------------------------------------
def bar(path, z0, sc, pts_uz, w, off_in, off_out):
    """Rectangular bar following the polyline pts_uz = [(u, zl)] on the wall (plan follows the path)."""
    rings = []
    n = len(pts_uz)
    for i, (u, zl) in enumerate(pts_uz):
        a = pts_uz[max(i - 1, 0)]
        b = pts_uz[min(i + 1, n - 1)]
        du, dz = b[0] - a[0], b[1] - a[1]
        l = math.hypot(du, dz) or 1.0
        nu, nz = -dz / l, du / l
        ring = []
        for (su, so) in ((1, off_out), (-1, off_out), (-1, off_in), (1, off_in)):
            uu = u + nu * w / 2 * su
            zz = zl + nz * w / 2 * su
            p, nn = path.at(sc + uu)
            ring.append((p[0] + nn[0] * so, p[1] + nn[1] * so, z0 + zz))
        rings.append(ring)
    return C.loft(rings, True, True)


def mullions(path, z0, bays, tier):
    out = []
    for b in bays:
        a, sp, rise = bay_params(b, tier)
        sc = b["s0"] + b["w"] / 2
        kind = b["kind"]
        arch = arch_curve(kind, a, sp, rise, 12)
        sub = arch[::2] + ([arch[-1]] if len(arch) % 2 == 0 else [])
        # frame: sill-to-springing jambs, arch head bar
        out.append(bar(path, z0, sc, [(-a + 0.12, 0.2), (-a + 0.12, sp)], 0.26, -0.40, -0.04))
        out.append(bar(path, z0, sc, [(a - 0.12, 0.2), (a - 0.12, sp)], 0.26, -0.40, -0.04))
        head = [(x * 0.985, z - 0.16) for x, z in sub]
        out.append(bar(path, z0, sc, head, 0.24, -0.40, -0.04))
        # transoms
        nt = 9 if b["corner"] else 2
        for zt_ in (sp, sp * 0.52):
            line = [(-a + 0.12 + (2 * a - 0.24) * i / (nt - 1), zt_) for i in range(nt)]
            out.append(bar(path, z0, sc, line, 0.2, -0.38, -0.05))
        # verticals
        nv = max(1, int(round(2 * a / 2.7)) - 1)
        for k in range(1, nv + 1):
            x = -a + 2 * a * k / (nv + 1)
            zt_ = arch_z(kind, a, sp, rise, x) - 0.2
            out.append(bar(path, z0, sc, [(x, 0.2), (x, zt_)], 0.16, -0.38, -0.05))
        # inner tracery arc (smaller concentric arch)
        a2, r2 = a * 0.6, rise * 0.62
        arc2 = arch_curve(kind, a2, sp * 1.0, r2, 8)
        out.append(bar(path, z0, sc, arc2[::2] + ([arc2[-1]] if len(arc2) % 2 == 0 else []), 0.14, -0.36, -0.07))
    return join(*out)


# ---------------------------------------------------------------- build -------------------------------------------
def _add(name, vf, material, coll, weld_it=True, smooth=False, extra_mats=(), top_cap=0, orient=False):
    v, f = vf
    if weld_it:
        v, f = weld(v, f)
    if orient:
        v, f = orient_solids(v, f)
    ob = C.make_object(name, v, f, material, coll, smooth_shade=False, recalc=not orient)
    for m in extra_mats:
        ob.data.materials.append(m)
    if smooth:
        shade(ob)
    return ob


def build():
    coll = C.collection(COLLECTION)
    ivory, stone, amber, parapet = C.mat("ivory"), C.mat("stone"), C.mat("amber"), C.mat("parapet")
    gold, water = C.mat("gold"), C.mat("water")

    # ---- foundation plate (top z=0, bottom -1.2) and plinth steps (open across the entry)
    fpoly = outline(C.FOUNDATION[0], C.FOUNDATION[1], FOUND_R, 0.0, n=12)
    _add("Podium_Foundation", slab_mesh(fpoly, 0.0, 1.0, 1.2, 1.2), stone, coll)
    fp, _ = coarse(Path(run_path(C.FOUNDATION[0] - 5.6, C.FOUNDATION[1] - 5.6, FOUND_R - 2.8, gap=26.0)))
    steps = join(open_tube(fp, 0.0, [(2.8, 0.0), (1.3, 0.0), (1.3, 0.15), (2.8, 0.15)]),
                 open_tube(fp, 0.0, [(1.3, 0.0), (-0.3, 0.0), (-0.3, 0.32), (1.3, 0.32)]))
    _add("Podium_Plinth", steps, stone, coll, weld_it=False)

    for ti, (zt, w, d) in enumerate(C.DECKS, start=1):
        z0 = zt - TIER_H
        hs, hc = TIER_H - 0.6, TIER_H - 0.3

        # wall-line run: rear edge = slab edge - inset, front edge set back (EDGE_F); y0 = plan centre of the wall rectangle
        yf, yr = EDGE_F[ti] + WALL_INSET, d / 2 - WALL_INSET
        ww, wd = w - 2 * WALL_INSET, yr - yf
        y0 = (yr + yf) / 2
        wr = SLAB_R - WALL_INSET
        path = Path(run_path(ww, wd, wr, y0=y0))
        runs = wall_runs(path, z0, hs)
        bays = layout(path, ww, wd, wr, ti, y0, runs)

        # ---- slab with sculpted fascia
        dpoly, dv = slab_dense(path, bays, EDGE_L[ti])
        sv, sf, ntop = slab_fascia(dpoly, dv, zt)
        sv, sf = weld(sv, sf, tol=1e-4)
        slab = C.make_object(f"Podium_Slab_T{ti}", sv, sf, ivory, coll, smooth_shade=False, recalc=False)
        slab.data.materials.append(stone)
        # top cap faces -> stone: faces whose centre is at z == zt and well inside
        for p in slab.data.polygons:
            c = p.center
            if abs(c.z - zt) < 1e-4 and p.normal.z > 0.9:
                p.material_index = 1
        shade(slab)

        # ---- hollow arcade skin
        av, af = arcade_skin(path, z0, bays, ti, hc, hs)
        # orientation check on a mid front face (normal must point away from the wall line)
        av, af = weld(av, af)
        tot = 0.0
        for f in af:
            pts = [Vector(av[i]) for i in f]
            nrm = Vector((0, 0, 0))
            for i in range(len(pts)):
                a_, b_ = pts[i], pts[(i + 1) % len(pts)]
                nrm += Vector(((a_.y - b_.y) * (a_.z + b_.z), (a_.z - b_.z) * (a_.x + b_.x), (a_.x - b_.x) * (a_.y + b_.y)))
            cen = sum(pts, Vector((0, 0, 0))) / len(pts)
            # outward = away from the tower axis in plan, restricted to faces facing mostly sideways
            out_dir = Vector((cen.x, cen.y, 0)).normalized()
            if abs(nrm.z) < 0.5 * nrm.length:
                tot += nrm.dot(out_dir)
        if tot < 0:
            af = [tuple(reversed(f)) for f in af]
        sv2, sf2 = hollow_shell(av, af, SKIN_T)
        _add(f"Podium_Piers_T{ti}", (sv2, sf2), ivory, coll, weld_it=False, smooth=True)

        # ---- amber glazing (thin shell behind the arcade)
        gsec = [(GLASS_OFF[0], -0.1), (GLASS_OFF[1], -0.1), (GLASS_OFF[1], TIER_H - 0.8), (GLASS_OFF[0], TIER_H - 0.8)]
        # the amber curtain wall runs continuously behind the arcade, also across the rib pockets (rib stands in front of it)
        sp_ = Path(path.p[::3] + ([path.p[-1]] if (len(path.p) - 1) % 3 else []))
        _add(f"Podium_Glazing_T{ti}", open_tube(sp_, z0, gsec), amber, coll, weld_it=False)

        # ---- gold mullions
        _add(f"Podium_Mullions_T{ti}", mullions(path, z0, bays, ti), gold, coll, weld_it=False)

        # ---- parapet band (glass on an ivory kerb) + coping
        h = PARAPET_T / 2
        kw = KERB_W / 2
        cw, ch = COPING[0] / 2, COPING[1]
        po = WALL_INSET - PARAPET_IN
        ppts = [(p[0] + n[0] * po, p[1] + n[1] * po) for p, n in zip(path.p, path.n)]
        free = [not rib_hit(x, y, zt + 0.9, 0.8) for x, y in ppts]       # parapet / coping stop at a rib
        pieces, cur = [], []
        for pt, f in zip(ppts, free):
            if f:
                cur.append(pt)
            elif cur:
                pieces.append(cur)
                cur = []
        if cur:
            pieces.append(cur)
        pv, cv = [], []
        for pc in pieces:
            if len(pc) < 3:
                continue
            pp = Path(pc)
            cpp, _m = coarse(pp)
            pv.append(open_tube(cpp, zt + KERB_H, [(-h, 0.0), (h, 0.0), (h, GLASS_H), (-h, GLASS_H)]))
            cv.append(open_tube(cpp, zt, [(-kw, 0.0), (kw, 0.0), (kw, KERB_H), (-kw, KERB_H)]))
            cv.append(open_tube(cpp, zt + KERB_H + GLASS_H, [(-cw, 0.0), (cw, 0.0), (cw, ch), (-cw, ch)]))
        _add(f"Podium_Parapet_T{ti}", join(*pv), parapet, coll, weld_it=False)
        _add(f"Podium_Coping_T{ti}", join(*cv), ivory, coll, weld_it=False)

        # ---- terrace detail: channel kerbs, paving lines, stepped corners (coarse path: straights collapse)
        W2, D2 = ww / 2, wd / 2
        cidx = [i for i, p in enumerate(path.p) if abs(p[0]) > W2 - wr + 1e-6 and abs(p[1] - y0) > D2 - wr + 1e-6]
        grp = []
        for i in cidx:
            if grp and i == grp[-1][1] + 1:
                grp[-1][1] = i
            else:
                grp.append([i, i])
        ext = 7
        forced = []
        for g0, g1 in grp:
            forced += [max(g0 - ext, 0), g0, g1, min(g1 + ext, len(path.p) - 1)]
        cp, cmap = coarse(path, forced)
        parts = []
        o_out, o_in = CH_OUT, CH_IN
        parts.append(open_tube(cp, zt, [(o_out, 0.0), (o_out - 0.34, 0.0), (o_out - 0.34, 0.30), (o_out, 0.30)]))
        parts.append(open_tube(cp, zt, [(o_in + 0.34, 0.0), (o_in, 0.0), (o_in, 0.30), (o_in + 0.34, 0.30)]))
        off = 0.9
        while off >= -MAX_IN[ti]:
            parts.append(open_tube(cp, zt, [(off + 0.07, 0.0), (off - 0.07, 0.0), (off - 0.07, 0.05), (off + 0.07, 0.05)]))
            off -= 2.1
        piers = [b["s0"] for b in bays] + [path.L]
        for s_ in piers[1:-1]:
            parts.append(box_at(path, s_, 0.9, -MAX_IN[ti], 0.14, zt, 0.05))
        for g0, g1 in grp:
            a0, a1 = cmap[max(g0 - ext, 0)], cmap[min(g1 + ext, len(path.p) - 1)]
            parts.append(strip(cp, zt, 1.75, -3.4, 0.30, a0, a1))
            parts.append(strip(cp, zt, 0.85, -1.6, 0.60, cmap[g0], cmap[g1]))
        _add(f"Podium_Terrace_T{ti}", join(*parts), stone, coll, weld_it=False, orient=True)
        wch = open_tube(cp, zt, [(o_out - 0.34, 0.05), (o_in + 0.34, 0.05), (o_in + 0.34, 0.20), (o_out - 0.34, 0.20)])
        _add(f"Podium_Water_T{ti}", wch, water, coll, weld_it=False)
    return coll
