"""Crown module (round 3): lotus crown on the tower roof.
  - Crown_Petal_##       outer ring: broad ivory leaf blades (6-9 m wide, 25-35 m tall, 2-4 m thick) that start on the glass
                         face below the roof (~+200) and wrap the top of the glass, tips curving outward (apex 226-236 m)
  - Crown_PetalInner_##  inner ring: shorter leaf blades set inside the outer ring (apex 222-228 m)
  - Crown_cap_*          layered amber/gold lotus bud (apex 232 m) inside the 16 x 24 m envelope: glass ogive, gold lattice,
                         three overlapping rings of amber bud scales
  - Crown_atrium_collar(+_rim)  gold inverted cone widening to an ivory saucer rim at +200 (reference 09)
  - Crown_roof_coping / gold trim / inlay / glow: roof-edge details
Zone +216..+240 m, EXCLUDING the six principal rib blades (ribs module). Z up, front = -Y.
All parameters at the top are PROPOSED builder choices (R06 only fixes the 16 x 24 m cap envelope and 240 m crown top).
"""
import math
import cl_common as C
from mathutils import Vector

COLLECTION = "Crown"

# ------------------------------------------------------------------ parameters (proposed) ----------
Z0 = C.TOWER_ROOF_Z                  # 216 roof
CAP_ENV_A, CAP_ENV_B = C.CAP_ENVELOPE[0] / 2, C.CAP_ENVELOPE[1] / 2   # 8 x 12 half-extents (R06 16 x 24)
SCALE_OUT = 0.9                      # outer bud-scale layer stands this far off the glass
CAP_A, CAP_B = CAP_ENV_A - SCALE_OUT - 0.6, CAP_ENV_B - SCALE_OUT - 0.6   # glass ogive half-extents
CAP_DRUM_H = 5.0                     # vertical glass drum under the ogive
CAP_TOP = 232.0                      # cap apex (R06: crown zone top 240)

# outer petals: (param angle deg on the roof superellipse, apex z, base width W, height H, thickness T)
OUTER = [   # 6 wrap-around petals on the glass face, in the windows the principal ribs leave free
    (86, 231.0, 11.0, 31.0, 2.6), (94, 229.5, 11.0, 29.0, 2.6), (266, 233.0, 10.4, 31.0, 2.6), (274, 231.0, 10.4, 29.0, 2.6),
    (196, 232.0, 11.0, 30.0, 2.6), (344, 230.5, 11.0, 29.0, 2.6),
]
ROOF = [    # 5 larger roof-standing petals just inside the parapet, behind the ribs
    (270, 238.5, 11.0, 22.5, 2.8), (90, 238.0, 11.0, 22.0, 2.8), (4, 236.5, 10.0, 20.5, 2.6), (176, 237.0, 10.0, 21.0, 2.6),
    (224, 236.0, 8.0, 20.0, 2.6),
]
INNER = [   # 2 smaller inner petals around the cap
    (34, 226.5, 6.4, 14.0, 2.0), (146, 227.0, 6.4, 14.5, 2.0),
]
H0 = 1.15            # hug offset: inner face of an outer petal stands this far outside the roof edge (clears coping/trim)
WRAP = 0.55          # petal edges bend this far toward the glass (curved face wrapping the tower top)
LEAN = 4.2           # inward lean of the upper half of an outer petal
FLICK = 1.4          # outward flick of the tip
CAP_CLEAR = 0.7      # min clearance of petal faces to the bud scales

# bud scale layers (n, z start, z end, offset from glass, phase)
SCALES = [
    (10, 216.6, 225.5, 0.90, 0.0),
    (10, 219.4, 228.6, 0.58, math.pi / 10),
    (8, 222.4, 231.4, 0.30, math.pi / 8),
]


# ------------------------------------------------------------------ geometry helpers ----------------
def ss(t):
    t = min(max(t, 0.0), 1.0)
    return t * t * (3 - 2 * t)


class Geo:
    def __init__(self):
        self.v, self.f = [], []

    def add(self, v, f):
        o = len(self.v)
        self.v.extend(v)
        self.f.extend([tuple(i + o for i in fc) for fc in f])


def _ell(a, b, n, z=0.0):
    return [(a * math.cos(2 * math.pi * i / n), b * math.sin(2 * math.pi * i / n), z) for i in range(n)]


def ring_sweep(poly, profile):
    """Sweep a (d, z) profile around a closed CCW polygon (x, y[, z]); d = outward offset. Closed solid ring."""
    n = len(poly)
    secs = []
    for i in range(n):
        p0, p1 = poly[(i - 1) % n], poly[(i + 1) % n]
        tx, ty = p1[0] - p0[0], p1[1] - p0[1]
        L = math.hypot(tx, ty) or 1.0
        nx, ny = ty / L, -tx / L
        x, y = poly[i][0], poly[i][1]
        secs.append([(x + nx * d, y + ny * d, z) for d, z in profile])
    m = len(profile)
    v = [p for s in secs for p in s]
    f = []
    for i in range(n):
        j = (i + 1) % n
        for k in range(m):
            k2 = (k + 1) % m
            f.append((i * m + k, j * m + k, j * m + k2, i * m + k2))
    return v, f


def tube(path, ups, w, t):
    """Square-section sweep with a per-point 'up' (outward) vector; w, t scalar or lists."""
    n = len(path)
    ws = w if isinstance(w, (list, tuple)) else [w] * n
    ts = t if isinstance(t, (list, tuple)) else [t] * n
    rings = []
    for i, p in enumerate(path):
        tan = (Vector(path[min(i + 1, n - 1)]) - Vector(path[max(i - 1, 0)])).normalized()
        side = tan.cross(Vector(ups[i]))
        if side.length < 1e-6:
            side = Vector((1, 0, 0))
        side.normalize()
        nor = side.cross(tan).normalized()
        c = Vector(p)
        hw, ht = ws[i] / 2, ts[i] / 2
        rings.append([tuple(c + side * hw + nor * ht), tuple(c - side * hw + nor * ht),
                      tuple(c - side * hw - nor * ht), tuple(c + side * hw - nor * ht)])
    return C.loft(rings)


def ogive_scale(t):
    return (1.0 - t ** 1.9) * (1.0 - 0.15 * t)


def cap_scale_at(z, zdrum, ztop):
    if z <= zdrum:
        return 1.0 - 0.03 * (z - Z0) / max(zdrum - Z0, 1e-6)
    t = (z - zdrum) / (ztop - zdrum)
    return 0.97 * ogive_scale(min(t, 1.0))


def ell_point(a, b, th, s, z, off=0.0):
    x, y = a * s * math.cos(th), b * s * math.sin(th)
    nx, ny = math.cos(th) / a, math.sin(th) / b
    L = math.hypot(nx, ny)
    return (x + nx / L * off, y + ny / L * off, z)


def outward(th, a, b):
    nx, ny = math.cos(th) / a, math.sin(th) / b
    L = math.hypot(nx, ny)
    return (nx / L, ny / L, 0.0)


def _roof_dims():
    try:
        import tower as T
        return T.ROOF_W / 2, T.ROOF_D / 2, T.SUPER_N
    except Exception:
        return C.TOWER_TOP[0] / 2 - 1.0, C.TOWER_TOP[1] / 2 - 1.0, 2.5


def roof_edge(th, inset, A=None, B=None, n=None):
    """Point and outward normal on the tower roof superellipse (read from tower.py), pushed `inset` m inward."""
    dA, dB, dn = _roof_dims()
    A, B, n = A or dA, B or dB, n or dn
    c, s = math.cos(th), math.sin(th)
    x = A * math.copysign(abs(c) ** (2 / n), c)
    y = B * math.copysign(abs(s) ** (2 / n), s)
    gx, gy = math.copysign((abs(x) / A) ** (n - 1), x) / A, math.copysign((abs(y) / B) ** (n - 1), y) / B
    L = math.hypot(gx, gy)
    nx, ny = gx / L, gy / L
    return (x - nx * inset, y - ny * inset), (nx, ny, 0.0)


ZDRUM = Z0 + CAP_DRUM_H


def cap_free(x, y, z, clear):
    """True when plan point (x, y) at height z is at least ~`clear` outside the bud (scales included)."""
    if z > CAP_TOP + 1:
        return True
    s = cap_scale_at(min(max(z, Z0), CAP_TOP), ZDRUM, CAP_TOP)
    a, b = CAP_A * s + SCALE_OUT + clear, CAP_B * s + SCALE_OUT + clear
    return (x / a) ** 2 + (y / b) ** 2 >= 1.0


# ------------------------------------------------------------------ leaf blades ---------------------
def leaf_section(W, T, wrap, K=9):
    """Crescent section as (s, d) list: outer face then inner face. s tangential, d outward from the inner-face line."""
    us = [-1 + 2 * k / (K - 1) for k in range(K)]
    outer = []
    for u in us:
        e = max(1 - u * u, 0.0)
        outer.append((u * W / 2, -wrap * u * u + T * e ** 0.5))
    inner = []
    for u in reversed(us[1:-1]):
        inner.append((u * W / 2, -wrap * u * u))
    return outer + inner


def leaf_width(u):
    """Plan width factor: rounded base (~62% of belly), belly at ~35% of height, then a curved pointed tip."""
    if u < 0.35:
        return 0.62 + 0.38 * math.sin(math.pi / 2 * u / 0.35)
    v = (u - 0.35) / 0.65
    return max((1.0 - v ** 1.7) ** 0.75, 0.03)


def leaf_thick(u):
    ramp = 0.55 + 0.45 * math.sin(math.pi / 2 * min(u / 0.16, 1.0))
    return max(ramp * (1.0 - 0.85 * max(u - 0.25, 0.0) ** 1.3 / 0.75 ** 1.3), 0.05)


def build_leaf(coll, name, th, ztop, W, H, T, inset, lean, flick, steps, inlay, glow, mat_name="ivory", edge_gold=True, push=0.0):
    base, nrm = roof_edge(th, inset)
    nx, ny = nrm[0], nrm[1]
    side = Vector((-ny, nx, 0.0))
    zb = ztop - H
    ctr = []
    for i in range(steps + 1):
        u = i / steps
        z = zb + H * u
        zz = (z - Z0) / max(ztop - Z0, 1e-6)
        lat = H0 + push - lean * ss(zz * 1.6) * (1.0 if z > Z0 else 0.0) + flick * ss((u - 0.55) / 0.45) ** 1.5
        # keep the inner face clear of the bud
        for _ in range(40):
            px, py = base[0] + nx * lat, base[1] + ny * lat
            if cap_free(px, py, z, CAP_CLEAR + T * 0.1):
                break
            lat += 0.25
        ctr.append(Vector((base[0] + nx * lat, base[1] + ny * lat, z)))
    rings = []
    cl_edges = ([], [])
    for i, c in enumerate(ctr):
        u = i / steps
        tan = (ctr[min(i + 1, steps)] - ctr[max(i - 1, 0)]).normalized()
        nn = side.cross(tan)
        if nn.length < 1e-6:
            nn = Vector((nx, ny, 0.0))
        nn.normalize()
        # make sure the section normal stays on the outward side
        if nn.dot(Vector((nx, ny, 0.0))) < 0:
            nn = -nn
        w, t = leaf_width(u), leaf_thick(u)
        wrap = WRAP * w
        sec = leaf_section(W * w, T * t, wrap)
        rings.append([tuple(c + side * s + nn * d) for s, d in sec])
        if edge_gold and 0.10 <= u <= 0.985:
            for k, sgn in enumerate((-1, 1)):
                s_e = sgn * W * w / 2 * 0.985
                cl_edges[k].append(tuple(c + side * s_e + nn * (-wrap + 0.02)))
    v, f = C.loft(rings, cap_bottom=True, cap_top=True)
    C.make_object(name, v, f, C.mat(mat_name), coll)
    if edge_gold:
        for pts in cl_edges:
            if len(pts) > 3:
                up = [(nx, ny, 0.0)] * len(pts)
                ev, ef = tube(pts, up, 0.30, 0.30)
                inlay.add(ev, ef)
    # amber glow strip on the inner (glass-facing) face, lower two thirds
    if glow is not None:
        sub, gw = [], []
        for i, c in enumerate(ctr):
            u = i / steps
            if 0.12 <= u <= 0.70:
                tan = (ctr[min(i + 1, steps)] - ctr[max(i - 1, 0)]).normalized()
                nn = side.cross(tan).normalized()
                if nn.dot(Vector((nx, ny, 0.0))) < 0:
                    nn = -nn
                sub.append(tuple(c - nn * 0.05))
                gw.append(max(W * leaf_width(u) * 0.30, 0.12))
        if len(sub) > 3:
            gv, gf = tube(sub, [(-nx, -ny, 0.0)] * len(sub), gw, 0.1)
            glow.add(gv, gf)
    return ctr


# ------------------------------------------------------------------ bud scales -----------------------
def scale_layer(n, za, zb, off, phase, geo_amber, geo_gold, zdrum):
    steps = 16
    for k in range(n):
        th = phase + 2 * math.pi * k / n
        nrm = outward(th, CAP_A, CAP_B)
        side = Vector((-nrm[1], nrm[0], 0.0))
        pts = []
        for i in range(steps + 1):
            u = i / steps
            z = za + (zb - za) * u
            s = cap_scale_at(z, zdrum, CAP_TOP)
            p = ell_point(CAP_A, CAP_B, th, s, z, off + 0.55 * ss((u - 0.75) / 0.25))
            pts.append(Vector(p))
        perim = 2 * math.pi * math.sqrt((CAP_A ** 2 + CAP_B ** 2) / 2) * cap_scale_at(za, zdrum, CAP_TOP)
        W = perim / n * 1.22
        rings, e0, e1 = [], [], []
        for i, c in enumerate(pts):
            u = i / steps
            tan = (pts[min(i + 1, steps)] - pts[max(i - 1, 0)]).normalized()
            nn = side.cross(tan).normalized()
            if nn.dot(Vector(nrm)) < 0:
                nn = -nn
            w = max(W * leaf_width(u * 0.98) * (1.0 - 0.28 * u), 0.04)
            t = max(0.55 * (1 - 0.7 * u), 0.08)
            sec = leaf_section(w, t, 0.18 * w / 4)
            rings.append([tuple(c + side * s + nn * d) for s, d in sec])
            if 0.06 <= u <= 0.99:
                e0.append(tuple(c - side * w / 2 * 0.97 + nn * 0.02))
                e1.append(tuple(c + side * w / 2 * 0.97 + nn * 0.02))
        v, f = C.loft(rings)
        geo_amber.add(v, f)
        for e in (e0, e1):
            ev, ef = tube(e, [nrm] * len(e), 0.20, 0.22)
            geo_gold.add(ev, ef)


# ------------------------------------------------------------------ atrium collar --------------------
def _atrium_fns():
    try:
        import tower as T
        return T.skin_y, T.ch_hw, T.ch_proj
    except Exception:
        def skin_y(z, x, rear):
            hx, hy = C.tower_half_extents(z)
            q = min(abs(x) / hx, 0.999999)
            return -hy * (1 - q ** 2.5) ** (1 / 2.5)

        def ch_hw(z):
            return 0.26 * C.tower_half_extents(z)[0]

        def ch_proj(z):
            return 2.8 + (1.6 - 2.8) * (z - 54.0) / 136.0
        return skin_y, ch_hw, ch_proj


def build_atrium_collar(coll):
    """Saucer-rim collar (reference 09): gold inverted cone that widens from the channel top (+184) up to an ivory
    saucer rim at +198..+200.4 (thick lip, flat top, rounded under-edge) that projects off the tower face."""
    skin_y, ch_hw, ch_proj = _atrium_fns()
    ZA, ZR0, ZR1 = 184.0, 197.2, 200.4
    cols = 25
    hc, pc = ch_hw(190.0), ch_proj(190.0)

    def ring(z, hw, proj, back):
        outer, bk = [], []
        for j in range(cols):
            x = -hw + 2 * hw * j / (cols - 1)
            u = min(abs(x) / hw, 1.0)
            ys = skin_y(z, x, False)
            outer.append((x, ys - proj * (1 - u * u) ** 0.6, z))
            bk.append((x, ys + back, z))
        return outer + list(reversed(bk[1:-1]))

    # gold cone body
    rings = []
    n = 12
    for i in range(n + 1):
        t = i / n
        e = t ** 1.5
        rings.append(ring(ZA + (ZR0 - ZA) * t, hc + 0.2 + 0.9 * e, pc + 0.2 + 2.2 * e, 0.35))
    v, f = C.loft(rings, cap_bottom=True, cap_top=True)
    C.make_object("Crown_atrium_collar", v, f, C.mat("gold"), coll)
    # ivory saucer rim: profile (dhw, dproj, z)
    prof = [(-0.2, -1.3, ZR0 - 0.2), (0.3, 0.5, ZR0 + 0.05), (0.6, 1.7, ZR0 + 0.45), (0.8, 2.3, ZR0 + 1.2),
            (0.7, 2.1, ZR1 - 0.3), (0.5, 1.5, ZR1), (-0.2, -0.8, ZR1)]
    hw0, pj0 = hc + 0.4, pc + 2.4
    rr = [ring(z, max(hw0 + dh, 0.5), max(pj0 + dp, 0.2), 0.35) for dh, dp, z in prof]
    v, f = C.loft(rr, cap_bottom=True, cap_top=True)
    C.make_object("Crown_atrium_collar_rim", v, f, C.mat("ivory"), coll)


# ------------------------------------------------------------------ main build ----------------------
def build():
    coll = C.collection(COLLECTION)
    zdrum = ZDRUM
    # ---- central glazed bud: drum + ogive, hollow shell (open at the roof)
    zs = [Z0 + (zdrum - Z0) * i / 3 for i in range(3)]
    N = 36
    og_n = 20
    for i in range(og_n + 1):
        zs.append(zdrum + (CAP_TOP - zdrum) * i / og_n)
    rings = []
    for z in zs:
        s = max(cap_scale_at(z, zdrum, CAP_TOP), 0.015)
        rings.append(_ell(CAP_A * s, CAP_B * s, N, z))
    v, f = C.loft(rings, cap_bottom=False, cap_top=True)
    C.make_object("Crown_cap_glass", v, f, C.mat("glass"), coll)

    # ---- gold lattice over the glass: meridians, crossed (lens) diagonals, ring bands at the layer breaks
    lat = Geo()
    off = 0.12
    zpath = [Z0 + (CAP_TOP - 0.4 - Z0) * i / 30 for i in range(31)]
    for k in range(12):
        th = 2 * math.pi * k / 12 + math.pi / 12
        path = [ell_point(CAP_A, CAP_B, th, cap_scale_at(z, zdrum, CAP_TOP), z, off) for z in zpath]
        ups = [outward(th, CAP_A, CAP_B)] * len(path)
        wv = [0.30 * (1 - 0.6 * i / 30) for i in range(len(path))]
        tv, tf = tube(path, ups, wv, 0.24)
        lat.add(tv, tf)
    for sgn in (-1, 1):
        for k in range(4):
            th0 = 2 * math.pi * k / 4 + math.pi / 4
            path, ups = [], []
            for i in range(31):
                u = i / 30
                z = Z0 + 0.4 + (CAP_TOP - 1.2 - Z0) * u
                th = th0 + sgn * 1.05 * u
                path.append(ell_point(CAP_A, CAP_B, th, cap_scale_at(z, zdrum, CAP_TOP), z, off + 0.04))
                ups.append(outward(th, CAP_A, CAP_B))
            tv, tf = tube(path, ups, 0.24, 0.22)
            lat.add(tv, tf)
    for zr, w in ((zdrum, 0.7), (Z0 + 9.4, 0.42), (Z0 + 12.6, 0.38), (Z0 + 14.6, 0.32)):
        s = cap_scale_at(zr, zdrum, CAP_TOP)
        poly = _ell(CAP_A * s, CAP_B * s, 48)
        rv, rf = ring_sweep(poly, [(0.02, zr - w / 2), (0.30, zr - w / 2), (0.30, zr + w / 2), (0.02, zr + w / 2)])
        lat.add(rv, rf)
    # gold finial needle at the apex
    fv, ff = tube([(0, 0, CAP_TOP - 0.6), (0, 0, CAP_TOP - 0.1), (0, 0, CAP_TOP + 0.5)], [(1, 0, 0)] * 3, [0.5, 0.35, 0.05], [0.5, 0.35, 0.05])
    lat.add(fv, ff)
    C.make_object("Crown_cap_lattice", lat.v, lat.f, C.mat("gold"), coll)

    # ---- layered amber bud scales (three overlapping rings), gold edge lines
    amber, goldscale = Geo(), Geo()
    for (n, za, zb, off, ph) in SCALES:
        scale_layer(n, za, zb, off, ph, amber, goldscale, zdrum)
    C.make_object("Crown_cap_bud_scales", amber.v, amber.f, C.mat("amber"), coll)
    C.make_object("Crown_cap_bud_scale_edges", goldscale.v, goldscale.f, C.mat("gold"), coll)

    # ---- ivory collar ring at the cap base (lip + conical underside)
    poly = _ell(CAP_ENV_A - 0.1, CAP_ENV_B - 0.1, 48)
    prof = [(-0.2, Z0 + 0.4), (0.1, Z0 + 1.0), (0.1, Z0 + 1.9), (-0.2, Z0 + 2.3)]
    rv, rf = ring_sweep(poly, prof)
    C.make_object("Crown_cap_collar", rv, rf, C.mat("ivory"), coll)

    # ---- roof-edge ivory coping + gold trim line (tower builds the glass parapet)
    trim = Geo()
    zp = Z0 + 1.2
    poly = [roof_edge(2 * math.pi * i / 96, 0.35)[0] for i in range(96)]
    cv, cf = ring_sweep(poly, [(-0.42, zp), (0.42, zp), (0.42, zp + 0.3), (-0.42, zp + 0.3)])
    C.make_object("Crown_roof_coping", cv, cf, C.mat("ivory"), coll)
    tv, tf = ring_sweep(poly, [(0.42, zp + 0.02), (0.55, zp + 0.02), (0.55, zp + 0.26), (0.42, zp + 0.26)])
    trim.add(tv, tf)

    # ---- petals
    inlay, glow = Geo(), Geo()
    for i, (ang, zt, w, h, t) in enumerate(OUTER):
        build_leaf(coll, "Crown_Petal_%02d" % (i + 1), math.radians(ang), zt, w, h, t, 0.0, LEAN, FLICK, 34, inlay, glow,
                   push=1.2 if i % 2 == 0 else 1.6)
    for i, (ang, zt, w, h, t) in enumerate(ROOF):
        build_leaf(coll, "Crown_Petal_%02d" % (len(OUTER) + i + 1), math.radians(ang), zt, w, h, t, 2.3, 1.8, 1.6, 28,
                   inlay, glow, push=0.0 if i % 2 == 0 else 0.9)
    for i, (ang, zt, w, h, t) in enumerate(INNER):
        h = zt - (Z0 - 0.3)            # stand on the roof slab (no dip into the glass)
        build_leaf(coll, "Crown_PetalInner_%02d" % (i + 1), math.radians(ang), zt, w, h, t, 2.6, 1.3, 1.6, 26, inlay, glow)

    C.make_object("Crown_petal_inlay_gold", inlay.v, inlay.f, C.mat("gold"), coll)
    C.make_object("Crown_roof_gold_trim", trim.v, trim.f, C.mat("gold"), coll)
    C.make_object("Crown_petal_glow_amber", glow.v, glow.f, C.mat("amber"), coll)

    # ---- amber glow inside the bud: ogive core + orb + collar uplight ring
    core_rings = []
    zc0, zc1 = Z0 + 0.6, Z0 + 13.0
    for i in range(14):
        t = i / 13
        z = zc0 + (zc1 - zc0) * t
        s = max(0.52 * (1 - t ** 1.5) * (1 - 0.3 * t), 0.02)
        core_rings.append(_ell(CAP_A * s, CAP_B * s, 20, z))
    v, f = C.loft(core_rings, cap_bottom=False, cap_top=True)
    C.make_object("Crown_cap_amber_core", v, f, C.mat("amber"), coll)
    orb = []
    zc, rr = Z0 + 4.5, 1.7
    for i in range(1, 10):
        ph = math.pi * i / 10
        orb.append(_ell(rr * math.sin(ph), rr * math.sin(ph), 14, zc - rr * math.cos(ph)))
    v, f = C.loft(orb)
    C.make_object("Crown_cap_amber_orb", v, f, C.mat("amber"), coll)
    rv, rf = ring_sweep(_ell(CAP_A + 0.2, CAP_B + 0.2, 48), [(0.0, Z0 + 0.05), (0.5, Z0 + 0.05), (0.5, Z0 + 0.35), (0.0, Z0 + 0.35)])
    C.make_object("Crown_cap_uplight_amber", rv, rf, C.mat("amber"), coll)

    # ---- gold collar at the top of the front atrium channel
    build_atrium_collar(coll)
