"""Crown Landmark TOWER module: flared curtainwall body +54..+216 m.

Profile: superellipse plan |x/hx|^N + |y/hy|^N = 1 (N = SUPER_N), half extents hx,hy from C.tower_half_extents(z)
(68x54 m at +54 -> 34x26 m at +216). R06 plan 13 shows an elliptical tower footprint; N=2.5 sits between ellipse and
rounded rectangle, which matches the broad-shouldered look of the elevations. Each 4.5 m storey bows outward by
BULGE_M (sin arch) to read as curved glass panels.
Parts (one object each):
  Tower_curtainwall_skin   glass shell, 96 plan points x 145 levels (ring index i = fixed plan angle, front centre = 0)
  Tower_storey_bands       37-1 gold floor-plate edge bands every 4.5 m (+54 .. +211.5)
  Tower_mullions           gold vertical mullions at fixed plan angles (follow surface), broken at channel/pod
  Tower_front_channel      amber glazed slot, front centre, +54..+190, projecting
  Tower_front_lattice      crossed gold double curves + side/top/bottom trim on the channel
  Tower_rear_pod           lens glass pod, rear centre, +62..+196
  Tower_rear_pod_gold      lens outline, crossed gold curves, storey arcs on the pod
  Tower_roof_plate         36 x 26 m roof slab, top at +216
  Tower_roof_parapet       thin parapet ring on the roof edge
"""
import math
import os
import cl_common as C

COLLECTION = "Tower"

# ---------------------------------------------------------------- parameters --------------------------
SUPER_N = 2.5          # plan superellipse exponent (2 = ellipse, large = rectangle)
NPTS = 96              # plan points per ring (front centre = index 0, rear centre = 48)
Z0, Z1 = C.TOWER_BASE_Z if hasattr(C, "TOWER_BASE_Z") else 54.0, C.TOWER_ROOF_Z
STOREY = C.TOWER_SPACING          # 4.5 m
SUB = 4                           # ring levels per storey
BULGE_M = 0.22                    # outward bow of each storey panel
MULL_STEP = 4                     # mullion every 4th plan point -> 24 mullions
MULL_W, MULL_D = 0.32, 0.38       # mullion tangential width / outward depth
BAND_H, BAND_D = 0.50, 0.42       # band height / outward depth
CH_Z0, CH_Z1 = 54.0, 190.0        # front channel extent
CH_HW_RATIO = 0.26                # channel half-width = ratio * tower half-width hx(z)
CH_PROJ0, CH_PROJ1 = 2.8, 1.6     # channel projection at base / top
POD_Z0, POD_Z1 = 62.0, 196.0      # rear lens pod extent
POD_HW = 8.5                      # pod max half width
POD_PROJ = 3.2                    # pod max projection
ROOF_INSET = 1.0                  # roof plate / parapet inset from the skin edge (each side)
ROOF_W, ROOF_D = C.TOWER_TOP[0] - 2 * ROOF_INSET, C.TOWER_TOP[1] - 2 * ROOF_INSET   # follows C.TOWER_TOP (40x30 at 42x32)
ASYM = os.environ.get("CL_ASYM", "0") not in ("", "0")   # experimental: glass body offset rearward at its base
ASYM_DY0, ASYM_P = float(os.environ.get("CL_ASYM_DY", 6.0)), 1.6
ROOF_T = 0.6                      # slab thickness (top at +216)
PARAPET_H, PARAPET_T = 1.2, 0.3
XN = 2 / SUPER_N


def yoff(z):
    """Local helper: rearward (+Y) centre offset of the glass body vs height; 0 unless CL_ASYM is set."""
    if not ASYM:
        return 0.0
    t = min(max((z - Z0) / (Z1 - Z0), 0.0), 1.0)
    return ASYM_DY0 * (1 - t) ** ASYM_P


def sgn(v):
    return 1.0 if v >= 0 else -1.0


def bul(z):
    f = ((z - Z0) / STOREY) % 1.0
    if abs(f - 1.0) < 1e-6:
        f = 0.0
    return BULGE_M * math.sin(math.pi * f)


def sp(z, i, bulge=True):
    """Skin point at height z, plan index i -> (x, y, nx, ny) with outward unit normal."""
    hx, hy = C.tower_half_extents(z)
    th = -math.pi / 2 + 2 * math.pi * i / NPTS
    c, s = math.cos(th), math.sin(th)
    x = hx * sgn(c) * abs(c) ** XN
    y = hy * sgn(s) * abs(s) ** XN
    gx = SUPER_N * abs(x / hx) ** (SUPER_N - 1) * sgn(x) / hx
    gy = SUPER_N * abs(y / hy) ** (SUPER_N - 1) * sgn(y) / hy
    g = math.hypot(gx, gy)
    nx, ny = gx / g, gy / g
    if bulge:
        b = bul(z)
        x += nx * b
        y += ny * b
    return x, y + yoff(z), nx, ny


def skin_y(z, x, rear):
    """Skin surface y at plan x on the rear (+) or front (-) face (includes storey bulge)."""
    hx, hy = C.tower_half_extents(z)
    q = min(abs(x) / hx, 0.999999)
    y = hy * (1 - q ** SUPER_N) ** (1 / SUPER_N) + bul(z)
    return (y if rear else -y) + yoff(z)


def levels():
    n = int(round((Z1 - Z0) / STOREY)) * SUB
    return [Z0 + (Z1 - Z0) * k / n for k in range(n + 1)]


def ch_hw(z):
    return CH_HW_RATIO * C.tower_half_extents(z)[0]


def ch_proj(z):
    t = (z - CH_Z0) / (CH_Z1 - CH_Z0)
    return CH_PROJ0 + (CH_PROJ1 - CH_PROJ0) * t


def ch_y(z, x):
    """Front channel outer surface y at (z, x), |x| <= ch_hw(z)."""
    u = min(abs(x) / ch_hw(z), 1.0)
    return skin_y(z, x, False) - ch_proj(z) * (1 - u * u) ** 0.7


def pod_w(z):
    s = (z - POD_Z0) / (POD_Z1 - POD_Z0)
    if s <= 0 or s >= 1:
        return 0.0
    return POD_HW * math.sin(math.pi * s) ** 0.85


def pod_p(z):
    s = (z - POD_Z0) / (POD_Z1 - POD_Z0)
    if s <= 0 or s >= 1:
        return 0.0
    return POD_PROJ * math.sin(math.pi * s) ** 0.8


def pod_y(z, x):
    w = max(pod_w(z), 1e-6)
    u = min(abs(x) / w, 1.0)
    return skin_y(z, x, True) + pod_p(z) * (1 - u * u) ** 0.8


class Mesh:
    def __init__(self):
        self.v, self.f = [], []

    def add(self, verts, faces):
        o = len(self.v)
        self.v.extend(verts)
        self.f.extend([tuple(i + o for i in fc) for fc in faces])


# ---------------------------------------------------------------- parts -----------------------------
def build_skin():
    rings = []
    for z in levels():
        rings.append([(*sp(z, i)[:2], z) for i in range(NPTS)])
    return C.loft(rings, cap_bottom=False, cap_top=False)


def build_bands():
    m = Mesh()
    k = 0
    while Z0 + k * STOREY < Z1 - 1e-6:       # 54 .. 211.5 ; the +216 edge is the roof slab
        z = Z0 + k * STOREY
        if k == 0:
            zl, zh = z, z + BAND_H          # sits on the deck, grows upward only
        else:
            zl, zh = z - BAND_H / 2, z + BAND_H / 2
        r0, r1, r2, r3 = [], [], [], []
        for i in range(NPTS):
            xl, yl, nx, ny = sp(zl, i)
            xh, yh, _, _ = sp(zh, i)
            r0.append((xl, yl, zl))
            r1.append((xl + nx * BAND_D, yl + ny * BAND_D, zl))
            r2.append((xh + nx * BAND_D, yh + ny * BAND_D, zh))
            r3.append((xh, yh, zh))
        v, f = C.loft([r0, r1, r2, r3], cap_bottom=False, cap_top=False)
        m.add(v, f)
        k += 1
    return m


def mull_ok(z, x, y):
    if y < 0 and CH_Z0 - 1 <= z <= CH_Z1 + 1 and abs(x) < ch_hw(z) + 0.7:
        return False
    if y > 0 and POD_Z0 - 1 <= z <= POD_Z1 + 1 and abs(x) < pod_w(z) + 0.7:
        return False
    return True


def build_mullions():
    m = Mesh()
    lv = levels()
    for i in range(0, NPTS, MULL_STEP):
        run = []
        for z in lv + [None]:
            ok = False
            if z is not None:
                x, y, nx, ny = sp(z, i)
                ok = mull_ok(z, x, y)
            if ok:
                tx, ty = -ny, nx
                cx, cy = x + nx * MULL_D * 0.4, y + ny * MULL_D * 0.4
                hw, hd = MULL_W / 2, MULL_D / 2
                run.append([(cx - nx * hd - tx * hw, cy - ny * hd - ty * hw, z),
                            (cx + nx * hd - tx * hw, cy + ny * hd - ty * hw, z),
                            (cx + nx * hd + tx * hw, cy + ny * hd + ty * hw, z),
                            (cx - nx * hd + tx * hw, cy - ny * hd + ty * hw, z)])
            else:
                if len(run) >= 2:
                    v, f = C.loft(run)
                    m.add(v, f)
                run = []
    return m


def build_channel():
    """Amber glazed slot: grid over u in [-1,1] and z; sealed top and bottom to the skin."""
    NU = 21
    rows = 91
    zs = [CH_Z0 + (CH_Z1 - CH_Z0) * j / (rows - 1) for j in range(rows)]
    v, f = [], []
    for z in zs:
        hw = ch_hw(z)
        for k in range(NU):
            x = hw * (-1 + 2 * k / (NU - 1))
            v.append((x, ch_y(z, x), z))
    for j in range(rows - 1):
        for k in range(NU - 1):
            a = j * NU + k
            f.append((a, a + 1, a + NU + 1, a + NU))
    # seal ends to the skin
    for j, down in ((0, True), (rows - 1, False)):
        z = zs[j]
        hw = ch_hw(z)
        base = len(v)
        for k in range(NU):
            x = hw * (-1 + 2 * k / (NU - 1))
            v.append((x, skin_y(z, x, False), z))
        for k in range(NU - 1):
            p0, p1 = j * NU + k, j * NU + k + 1
            s0, s1 = base + k, base + k + 1
            if down:
                f.append((s0, s1, p1, p0))
            else:
                f.append((p0, p1, s1, s0))
    return v, f


def strip(points, up, w, t):
    """Rectangular gold strip along points. up picks the section orientation (use the outward normal)."""
    return C.blade(points, [w] * len(points), [t] * len(points), up=up, cap=True)


def build_front_lattice():
    m = Mesh()
    zs = [CH_Z0 + 1.0 + (CH_Z1 - CH_Z0 - 2.0) * j / 90 for j in range(91)]
    period = 34.0                                 # crossing every 34 m -> lens cells between
    for sign in (1, -1):
        for off in (-0.45, 0.45):                 # double curve
            pts = []
            for z in zs:
                hw = ch_hw(z)
                x = sign * 0.88 * hw * math.sin(math.pi * (z - CH_Z0) / period) + off
                pts.append((x, ch_y(z, x) - 0.12, z))
            v, f = strip(pts, (0, -1, 0), 0.32, 0.30)
            m.add(v, f)
    # fine secondary lattice: single thin curves, 3 crossings per main period
    for sign in (1, -1):
        pts = []
        for z in zs:
            x = sign * 0.55 * ch_hw(z) * math.sin(math.pi * (z - CH_Z0) / (period / 3))
            pts.append((x, ch_y(z, x) - 0.08, z))
        v, f = strip(pts, (0, -1, 0), 0.18, 0.16)
        m.add(v, f)
    # side trims (edges of the slot)
    for sgn_ in (1, -1):
        pts = []
        for z in [CH_Z0 + (CH_Z1 - CH_Z0) * j / 45 for j in range(46)]:
            x = sgn_ * ch_hw(z)
            pts.append((x, skin_y(z, x, False) - 0.15, z))
        v, f = strip(pts, (0, -1, 0), 0.55, 0.45)
        m.add(v, f)
    # top and bottom rims
    for z in (CH_Z0 + 0.25, CH_Z1):
        hw = ch_hw(z)
        pts = []
        for k in range(21):
            x = hw * (-1 + 2 * k / 20)
            pts.append((x, ch_y(z, x) - 0.1, z))
        v, f = strip(pts, (0, 0, 1), 0.7, 0.6)
        m.add(v, f)
    # storey ties across the slot (fine horizontal lines every 4.5 m)
    k = 1
    while Z0 + k * STOREY < CH_Z1 - 1:
        z = Z0 + k * STOREY
        hw = ch_hw(z)
        pts = [(hw * (-1 + 2 * q / 20), ch_y(z, hw * (-1 + 2 * q / 20)) - 0.05, z) for q in range(21)]
        v, f = strip(pts, (0, 0, 1), 0.3, 0.25)
        m.add(v, f)
        k += 1
    return m


def build_pod():
    NU = 17
    eps = 0.15
    rows = 69
    zs = [POD_Z0 + (POD_Z1 - POD_Z0) * j / (rows - 1) for j in range(rows)]
    v, f = [], []
    for z in zs:
        w = max(pod_w(z), eps)
        for k in range(NU):
            x = w * (-1 + 2 * k / (NU - 1))
            v.append((x, pod_y(z, x), z))
    for j in range(rows - 1):
        for k in range(NU - 1):
            a = j * NU + k
            f.append((a, a + NU, a + NU + 1, a + 1))      # outward = +y
    return v, f


def build_pod_gold():
    m = Mesh()
    zs = [POD_Z0 + (POD_Z1 - POD_Z0) * j / 90 for j in range(1, 90)]
    up = (0, 1, 0)
    # lens outline
    for sgn_ in (1, -1):
        pts = []
        for z in zs:
            x = sgn_ * max(pod_w(z), 0.2)
            pts.append((x, pod_y(z, x) + 0.05, z))
        v, f = strip(pts, up, 0.55, 0.45)
        m.add(v, f)
    # crossed gold curves: x = +-0.82 w(z) sin(3 pi s) -> two crossings inside the lens
    for sign in (1, -1):
        for off in (-0.4, 0.4):
            pts = []
            for z in zs:
                s = (z - POD_Z0) / (POD_Z1 - POD_Z0)
                w = pod_w(z)
                x = sign * 0.82 * w * math.sin(3 * math.pi * s) + off * (w / POD_HW)
                pts.append((x, pod_y(z, x) + 0.1, z))
            v, f = strip(pts, up, 0.30, 0.28)
            m.add(v, f)
    # central vertical mullion
    pts = [(0.0, pod_y(z, 0.0) + 0.08, z) for z in zs]
    v, f = strip(pts, up, 0.30, 0.28)
    m.add(v, f)
    # storey arcs across the pod
    k = 0
    while True:
        z = Z0 + k * STOREY
        k += 1
        if z < POD_Z0 + 2:
            continue
        if z > POD_Z1 - 2:
            break
        w = pod_w(z)
        pts = [(w * (-1 + 2 * q / 16), pod_y(z, w * (-1 + 2 * q / 16)) + 0.05, z) for q in range(17)]
        v, f = strip(pts, (0, 0, 1), 0.28, 0.26)
        m.add(v, f)
    return m


def build_roof():
    z1, z0 = Z1, Z1 - ROOF_T
    n = SUPER_N
    ring_top, ring_bot = [], []
    for i in range(NPTS):
        th = -math.pi / 2 + 2 * math.pi * i / NPTS
        c, s = math.cos(th), math.sin(th)
        x = ROOF_W / 2 * sgn(c) * abs(c) ** (2 / n)
        y = ROOF_D / 2 * sgn(s) * abs(s) ** (2 / n)
        ring_top.append((x, y, z1))
        ring_bot.append((x, y, z0))
    slab = C.loft([ring_bot, ring_top])
    # parapet: closed thin wall
    r = []
    for (zz, off) in ((z1, 0.2 + PARAPET_T), (z1 + PARAPET_H, 0.2 + PARAPET_T),
                      (z1 + PARAPET_H, 0.2), (z1, 0.2)):
        ring = []
        for i in range(NPTS):
            th = -math.pi / 2 + 2 * math.pi * i / NPTS
            c, s = math.cos(th), math.sin(th)
            x = ROOF_W / 2 * sgn(c) * abs(c) ** (2 / n)
            y = ROOF_D / 2 * sgn(s) * abs(s) ** (2 / n)
            # inset by off along the radial direction (approx. normal)
            L = math.hypot(x / (ROOF_W / 2) ** 2, y / (ROOF_D / 2) ** 2)
            ring.append((x - off * x / (ROOF_W / 2) ** 2 / L, y - off * y / (ROOF_D / 2) ** 2 / L, zz))
        r.append(ring)
    parapet = C.loft(r, cap_bottom=False, cap_top=False)
    return slab, parapet


def tower_glass():
    """Tower-local blue glass: more opaque and saturated than the shared 55% glass so Workbench/material-colour
    renders read as blue glass instead of washed-out grey."""
    import bpy
    m = bpy.data.materials.get("CL_tower_glass")
    if m:
        return m
    rgba = (0.07, 0.25, 0.46, float(os.environ.get("CL_GLASS_A", 0.82)))
    m = bpy.data.materials.new("CL_tower_glass")
    m.use_nodes = True
    b = m.node_tree.nodes.get("Principled BSDF")
    b.inputs["Base Color"].default_value = rgba
    b.inputs["Roughness"].default_value = 0.06
    b.inputs["Alpha"].default_value = rgba[3]
    m.diffuse_color = rgba
    m.metallic = 0.3
    m.roughness = 0.2
    return m


def build():
    coll = C.collection(COLLECTION)
    v, f = build_skin()
    C.make_object("Tower_curtainwall_skin", v, f, tower_glass(), coll, smooth_shade=True, recalc=False)
    b = build_bands()
    C.make_object("Tower_storey_bands", b.v, b.f, C.mat("gold"), coll, smooth_shade=False, recalc=False)
    mm = build_mullions()
    C.make_object("Tower_mullions", mm.v, mm.f, C.mat("gold"), coll, smooth_shade=False, recalc=False)
    v, f = build_channel()
    C.make_object("Tower_front_channel", v, f, C.mat("amber"), coll, smooth_shade=True, recalc=False)
    fl = build_front_lattice()
    C.make_object("Tower_front_lattice", fl.v, fl.f, C.mat("gold"), coll, smooth_shade=True)
    v, f = build_pod()
    C.make_object("Tower_rear_pod", v, f, C.mat("glass"), coll, smooth_shade=True, recalc=False)
    pg = build_pod_gold()
    C.make_object("Tower_rear_pod_gold", pg.v, pg.f, C.mat("gold"), coll, smooth_shade=True)
    slab, parapet = build_roof()
    C.make_object("Tower_roof_plate", slab[0], slab[1], C.mat("stone"), coll, smooth_shade=False, recalc=False)
    C.make_object("Tower_roof_parapet", parapet[0], parapet[1], C.mat("parapet"), coll, smooth_shade=False,
                  recalc=False)
