"""Crown Landmark ribs (round 2): six bold ivory blades Rib_R1..Rib_R6 (flat foot z=0 -> leaf-shaped crown petal) and
eight thick swooping corner fins Fin_* (two per deck-3 corner).

Rib construction
  * The blade is a loft of HORIZONTAL plan rings (flat foot at z=0 by construction, plan widths are the numbers the brief asks for).
    Ring = super-ellipse with plan length L(z) along the rib's long axis (psi) and thickness T(z) across it.
  * Centre line: pchip through hand-set anchors (z, x, y). For the x-aligned ribs (R1,R2,R5,R6; psi = 0) the anchors describe the
    OUTER edge, so the outer edge is a straight leaning diagonal and the inner edge is carved by the width law.
    For the y-aligned side ribs (R3,R4; psi = 90 deg) the anchors are the centre line.
  * Glass hugging: every ring above z=52 is pushed outward along the glass normal until its closest vertex is CLEAR (1.0 m, gap
    to the skin incl. storey bulge >= 0.8 m) from the tower glass; the push ramps off between z=205 and z=222 so the tips land
    exactly on C.RIBS (the last 30 m may touch/overlap the crown zone).
  * Crown petal: above ZLEAF the plan length follows L0*(1-s^1.5), thickness T0*(1-s^1.3): a broad leaf with a sharp point at the
    target tip; the centre line ends with a slight outward curve (inner edge sweeps outward to the tip).
  * Tip x,y,z are exactly C.RIBS (apex vertex).
Fins: thick ribbons rising from the deck-3 (+54) corner edge, sweeping inward/up along a radial ray and hugging the glass base.
"""
import math
import json
import numpy as np
from mathutils import Vector
import cl_common as C

COLLECTION = "Ribs"

CLEAR = 1.0               # ring-vertex clearance to the (bulge-free) glass skin used by the push; measured gap >= 0.8
SKIN_BULGE = 0.22         # storey bow of the tower skin (tower.py BULGE_M)
SUPER_N = 2.5             # tower plan superellipse exponent (tower.py SUPER_N)
PUSH_Z0, PUSH_FULL, PUSH_END = 52.0, 205.0, 222.0
NSEC = 24                 # points per ring


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


def pchip(knots, x):
    """Monotone cubic Hermite through (x, y) knots, linear extrapolation."""
    xs = [k[0] for k in knots]
    ys = [k[1] for k in knots]
    n = len(xs)
    d = [(ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]) for i in range(n - 1)]
    m = [d[0]] + [(2 * d[i - 1] * d[i] / (d[i - 1] + d[i]) if d[i - 1] * d[i] > 0 else 0.0) for i in range(1, n - 1)] + [d[-1]]
    if x <= xs[0]:
        return ys[0] + m[0] * (x - xs[0])
    for i in range(n - 1):
        if x <= xs[i + 1]:
            h = xs[i + 1] - xs[i]
            t = (x - xs[i]) / h
            h00, h10, h01, h11 = 2 * t**3 - 3 * t**2 + 1, t**3 - 2 * t**2 + t, -2 * t**3 + 3 * t**2, t**3 - t**2
            return h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]
    return ys[-1]


# ------------------------------------------------------------------ glass model (matches tower.py) -----
_gc = {}


def _glass_poly(z):
    zq = round(min(max(z, 54.0), C.TOWER_ROOF_Z) * 4) / 4
    if zq not in _gc:
        hx, hy = C.tower_half_extents(zq)
        th = np.linspace(0, 2 * np.pi, 721)[:-1]
        c, s = np.cos(th), np.sin(th)
        xn = 2.0 / SUPER_N
        px = hx * np.sign(c) * np.abs(c) ** xn
        py = hy * np.sign(s) * np.abs(s) ** xn
        _gc[zq] = (hx, hy, px, py)
    return _gc[zq]


def glass_query(x, y, z):
    """(signed plan distance to the glass skin (>0 outside, bulge included), outward unit normal)."""
    hx, hy, px, py = _glass_poly(z)
    dx, dy = x - px, y - py
    d2 = dx * dx + dy * dy
    i = int(np.argmin(d2))
    d = math.sqrt(float(d2[i]))
    inside = (abs(x) / hx) ** SUPER_N + (abs(y) / hy) ** SUPER_N < 1.0
    if d < 1e-9:
        return -SKIN_BULGE, 1.0, 0.0
    nx, ny = dx[i] / d, dy[i] / d
    if inside:
        return -d - SKIN_BULGE, -nx, -ny
    return d - SKIN_BULGE, nx, ny


def glass_sdf(x, y, z):
    return glass_query(x, y, z)[0]


# ------------------------------------------------------------------ principal rib specification --------
# Anchors are for the LEFT-hand rib (x < 0), in 240-m "design height" zz; mirrored for the right-hand ribs and the z axis is
# scaled by tip_z/240. psi=0: x,y anchor the OUTER edge (x) and centre (y); psi=90: centre line.
YLAG_FRONT = 2.4
YLAG_REAR = 2.4
FRONT = dict(
    psi=0.0, edge=True, ylag=YLAG_FRONT,
    L=[(0, 27.0), (6, 25.0), (20, 19.5), (45, 14.0), (80, 12.0), (130, 11.5), (170, 10.8), (190, 11.4)],
    T=[(0, 8.2), (12, 7.4), (40, 5.4), (90, 4.5), (150, 4.1), (190, 4.7)],
    leaf=(190.0, 11.4, 4.7),
    A=[(0, -71.5, -40.0), (56, -60.0, -29.8), (84, -50.0, -24.5), (112, -34.0, -19.6), (150, -22.0, -16.6), (190, -16.4, -15.0),
       (206, -15.0, -14.5), (220, -13.4, -13.8), (231, -13.0, -13.3), (240, -14.0, -13.0)],
)
SIDE = dict(
    psi=90.0, edge=False,
    L=[(0, 21.0), (6, 19.0), (20, 14.5), (45, 11.0), (80, 9.8), (130, 9.4), (170, 9.6), (196, 10.4)],
    T=[(0, 6.6), (12, 6.0), (40, 4.4), (90, 3.7), (150, 3.5), (196, 4.1)],
    leaf=(196.0, 10.4, 4.1),
    A=[(0, -64.0, 6.0), (57, -52.0, 5.9), (115, -33.0, 5.6), (150, -24.5, 5.5), (190, -21.0, 5.2),
       (212, -21.4, 5.1), (228, -24.2, 5.0), (240, -27.0, 5.0)],
)
REAR = dict(
    psi=0.0, edge=True,
    L=[(0, 24.0), (6, 21.8), (20, 16.5), (45, 12.5), (80, 11.5), (130, 11.0), (170, 10.6), (196, 10.8)],
    T=[(0, 7.2), (12, 6.6), (40, 5.0), (90, 4.2), (150, 3.9), (196, 4.5)],
    leaf=(196.0, 10.8, 4.5),
    A=[(0, -52.0, 44.0), (30, -54.0, 40.5), (56, -54.0, 38.0), (84, -46.0, 31.5), (112, -36.0, 24.5), (150, -24.0, 17.4), (190, -19.0, 15.6),
       (206, -17.4, 15.9), (220, -14.2, 17.2), (231, -13.0, 18.4), (240, -13.0, 19.0)],
)
SPEC = {"R1": FRONT, "R2": FRONT, "R3": SIDE, "R4": SIDE, "R5": REAR, "R6": REAR}


def sgnpow(v, p):
    return math.copysign(abs(v) ** p, v)


def sec_pts(cx, cy, L, T, psi, nexp):
    a, b = L / 2.0, T / 2.0
    ca, sa = math.cos(math.radians(psi)), math.sin(math.radians(psi))
    out = []
    for k in range(NSEC):
        th = 2 * math.pi * k / NSEC
        u = a * sgnpow(math.cos(th), 2.0 / nexp)
        v = b * sgnpow(math.sin(th), 2.0 / nexp)
        out.append((cx + u * ca - v * sa, cy + u * sa + v * ca))
    return out


def width_laws(sp, zz):
    zl, L0, T0 = sp["leaf"]
    if zz <= zl:
        return pchip(sp["L"], zz), pchip(sp["T"], zz)
    s = min((zz - zl) / (240.0 - zl), 1.0)
    return L0 * (1 - s) ** 0.78, T0 * (1 - s) ** 0.72


def zz_list():
    z = list(np.arange(0.0, 150.0, 2.5)) + list(np.arange(150.0, 190.0, 2.0)) + list(np.arange(190.0, 232.0, 1.0)) \
        + list(np.arange(232.0, 239.6, 0.6)) + [239.5]
    out = []
    for v in z:
        if not out or v > out[-1] + 1e-6:
            out.append(float(v))
    return out


def rib_geometry(rid, debug=False):
    foot, tip, tz = C.RIBS[rid]
    sp = SPEC[rid]
    sx = 1.0 if foot[0] > 0 else -1.0
    k = tz / 240.0
    ax = [(z, -sx * x) for z, x, y in sp["A"]]
    ay = [(z, y) for z, x, y in sp["A"]]
    if "ylag" in sp:                      # y lags x: near-planar A-frame low down, sweeps to the tip in the top third
        yf, yt, ex = foot[1], tip[1], sp["ylag"]
        ay = [(float(z), yf + (yt - yf) * (z / 240.0) ** ex) for z in range(0, 241, 10)]
    zzs = zz_list()
    n = len(zzs)
    cx, cy, zs, Ls, Ts, nx_ = [], [], [], [], [], []
    for zz in zzs:
        L, T = width_laws(sp, zz)
        qx, qy = pchip(ax, zz), pchip(ay, zz)
        if sp["edge"]:
            qx += (-sx) * L / 2.0          # inward = toward x=0
        cx.append(qx)
        cy.append(qy)
        zs.append(zz * k)
        Ls.append(L)
        Ts.append(T)
        nx_.append(3.0 - 0.8 * ss((zz - 150.0) / 85.0))
    # clearance push (outward along glass normal)
    def push(i):
        z = zs[i]
        w = 1.0 - ss((z - PUSH_FULL) / (PUSH_END - PUSH_FULL))
        if z < PUSH_Z0 or w <= 0:
            return 0.0
        tot = 0.0
        for _ in range(14):
            pts = sec_pts(cx[i], cy[i], Ls[i], Ts[i], sp["psi"], nx_[i])
            worst = min(((*glass_query(x, y, z),) for x, y in pts), key=lambda r: r[0])
            if worst[0] >= CLEAR:
                break
            d = (CLEAR - worst[0]) * w
            cx[i] += worst[1] * d
            cy[i] += worst[2] * d
            tot += d
        return tot
    raw = list(zip(cx, cy))
    pushes = [push(i) for i in range(n)]
    # smooth the centre line through the hug zone, then re-establish clearance
    i0 = next(i for i, z in enumerate(zzs) if z >= 90.0)
    i1 = next(i for i, z in enumerate(zzs) if z >= 222.0)
    for _ in range(18):
        sx_, sy_ = cx[:], cy[:]
        for i in range(i0, i1):
            cx[i] = 0.25 * sx_[i - 1] + 0.5 * sx_[i] + 0.25 * sx_[i + 1]
            cy[i] = 0.25 * sy_[i - 1] + 0.5 * sy_[i] + 0.25 * sy_[i + 1]
    pushes2 = [push(i) for i in range(n)]
    if debug:
        for i in range(0, n, 6):
            print(rid, round(zs[i], 1), "raw", [round(v, 1) for v in raw[i]], "push", round(pushes[i], 2), "->",
                  round(cx[i], 1), round(cy[i], 1), "L", round(Ls[i], 1), "T", round(Ts[i], 1), "p2", round(pushes2[i], 2))
    rings = []
    for i in range(n):
        pts = sec_pts(cx[i], cy[i], Ls[i], Ts[i], sp["psi"], nx_[i])
        rings.append([(x, y, zs[i]) for x, y in pts])
    return rings, (tip[0], tip[1], tz)


def build_rib(rid, coll):
    rings, tipv = rib_geometry(rid)
    n = NSEC
    verts = [p for r in rings for p in r]
    apex = len(verts)
    verts.append(tipv)
    faces = [tuple(range(n - 1, -1, -1))]                 # flat foot cap at z=0
    for k in range(len(rings) - 1):
        for i in range(n):
            a, b = k * n + i, k * n + (i + 1) % n
            faces.append((a, b, b + n, a + n))
    base = (len(rings) - 1) * n
    for i in range(n):
        faces.append((base + i, base + (i + 1) % n, apex))
    return C.make_object("Rib_" + rid, verts, faces, C.mat("ivory"), coll)


# ------------------------------------------------------------------ flare fins -------------------------
DECK3 = C.DECKS[2]           # (54, 105, 76)
FIN_Z0 = 54.0
FIN_RISE = 1.0      # z(u) = u^FIN_RISE: slow start, so the fin swoops out of the deck edge
FIN_SWOOP = 0.95     # radial run-in exponent


def fin_path(ang_deg, corner, zend, n=56):
    """Concave ribbon from the deck-3 corner region to the glass at zend. corner = (sx, sy) signs."""
    sx, sy = corner
    base = math.atan2(DECK3[2] / 2, DECK3[1] / 2)
    a = base + math.radians(ang_deg)
    dx, dy = math.cos(a), math.sin(a)
    ex, ey = DECK3[1] / 2 - 3.0, DECK3[2] / 2 - 3.0
    t_edge = min(ex / abs(dx) if abs(dx) > 1e-6 else 1e9, ey / abs(dy) if abs(dy) > 1e-6 else 1e9)
    R0 = t_edge

    def hug_r(z, clr):
        lo, hi = 0.0, 90.0
        for _ in range(30):
            mid = (lo + hi) / 2
            if glass_sdf(sx * dx * mid, sy * dy * mid, z) > clr:
                hi = mid
            else:
                lo = mid
        return hi

    pts = []
    for i in range(n + 1):
        u = i / n
        z = FIN_Z0 - 0.5 + (zend - FIN_Z0 + 0.5) * u ** FIN_RISE
        clr = 1.1 + 0.4 * (1 - u)
        Rh = hug_r(max(z, 54), clr)
        R_hug54 = hug_r(54.0, clr)
        R = Rh + (R0 - R_hug54) * (1 - u) ** FIN_SWOOP
        pts.append((sx * dx * R, sy * dy * R, z))
    return pts, (sx * dx, sy * dy)


def octagon(hw, ht):
    c = 0.45 * min(hw, ht)
    return [(hw, -ht + c), (hw, ht - c), (hw - c, ht), (-hw + c, ht),
            (-hw, ht - c), (-hw, -ht + c), (-hw + c, -ht), (hw - c, -ht)]


def sweep(path, widths, thicks, side_h):
    up = Vector((0, 0, 1))
    n = len(path)
    rings = []
    for i, p in enumerate(path):
        tan = (Vector(path[min(i + 1, n - 1)]) - Vector(path[max(i - 1, 0)])).normalized()
        s = Vector(side_h)
        s = s - tan * s.dot(tan)
        if s.length < 1e-6:
            s = Vector((1, 0, 0))
        s.normalize()
        nor = s.cross(tan).normalized()
        c = Vector(p)
        rings.append([tuple(c + s * a + nor * b) for a, b in octagon(widths[i] / 2, thicks[i] / 2)])
    return C.loft(rings, cap_bottom=True, cap_top=True)


FIN_ZA, FIN_WA, FIN_ZB, FIN_WB = {-1: 100.0, 1: 148.0}, {-1: 8.0, 1: 14.0}, {-1: 90.0, 1: 130.0}, {-1: 7.0, 1: 12.0}
FIN_DEFS = []
for _name, _sx, _sy in (("FL", -1, -1), ("FR", 1, -1), ("RL", -1, 1), ("RR", 1, 1)):
    FIN_DEFS += [
        # name, corner, ray angle off the deck-3 diagonal (deg), top z, base width, thickness
        (f"Fin_{_name}_a", (_sx, _sy), 17.0, FIN_ZA[_sy], FIN_WA[_sy], 2.6),
        (f"Fin_{_name}_b", (_sx, _sy), -17.0, FIN_ZB[_sy], FIN_WB[_sy], 2.4),
    ]


def build_fin(name, corner, ang, zend, w0, t0, coll):
    pts, ray = fin_path(ang, corner, zend)
    n = len(pts)
    widths, thicks = [], []
    for i in range(n):
        u = i / (n - 1)
        wv = w0 * (1 - u ** 1.6) ** 0.9 if u < 0.985 else 0.3
        widths.append(max(0.3, wv))
        thicks.append(max(0.25, t0 * (1 - 0.55 * ss(u)) * (1 - 0.8 * ss((u - 0.8) / 0.2))))
    side_h = (-ray[1], ray[0], 0.0)
    # keep every section vertex >= 1.0 m (>= 0.8 m measured) off the glass: slide the section outward along the ray
    for i in range(n):
        for _ in range(40):
            if pts[i][2] < 54.3:
                break
            c = Vector(pts[i])
            tan = (Vector(pts[min(i + 1, n - 1)]) - Vector(pts[max(i - 1, 0)])).normalized()
            s_ = Vector(side_h)
            s_ = (s_ - tan * s_.dot(tan)).normalized()
            nor = s_.cross(tan).normalized()
            vs_ = [c + s_ * a_ + nor * b_ for a_, b_ in octagon(widths[i] / 2, thicks[i] / 2)]
            worst = min(glass_sdf(p.x, p.y, p.z) for p in vs_)
            if worst >= 1.0:
                break
            d = (1.0 - worst) * 0.9 + 0.02
            pts[i] = (pts[i][0] + ray[0] * d, pts[i][1] + ray[1] * d, pts[i][2])
    v, f = sweep(pts, widths, thicks, side_h)
    return C.make_object(name, v, f, C.mat("ivory"), coll)


# ------------------------------------------------------------------ measure -----------------------------
def section_extents(vs, es, z):
    pts = []
    for a, b in es:
        za, zb = vs[a].z, vs[b].z
        if (za - z) * (zb - z) < 0:
            t = (z - za) / (zb - za)
            p = vs[a] + (vs[b] - vs[a]) * t
            pts.append((p.x, p.y))
    if len(pts) < 3:
        return None
    P = np.array(pts)
    Pc = P - P.mean(axis=0)
    w, v = np.linalg.eigh(np.cov(Pc.T))
    e1 = Pc @ v[:, 1]
    e0 = Pc @ v[:, 0]
    return round(float(e1.max() - e1.min()), 1), round(float(e0.max() - e0.min()), 1), [round(float(x), 1) for x in P.mean(axis=0)]


def measure(coll):
    rep = {}
    for ob in coll.objects:
        vs = [ob.matrix_world @ v.co for v in ob.data.vertices]
        es = [(e.vertices[0], e.vertices[1]) for e in ob.data.edges]
        lo = [min(p[i] for p in vs) for i in range(3)]
        hi = [max(p[i] for p in vs) for i in range(3)]
        tipv = max(vs, key=lambda p: p.z)
        pen = 9e9
        pen_inner = 9e9
        for p in vs:
            if p.z >= 54.0:
                sd = glass_sdf(p.x, p.y, p.z)
                pen = min(pen, sd)
                if p.z <= 210.0:
                    pen_inner = min(pen_inner, sd)
        d = {"min": [round(x, 1) for x in lo], "max": [round(x, 1) for x in hi],
             "tip": [round(tipv.x, 2), round(tipv.y, 2), round(tipv.z, 2)],
             "min_gap_to_glass_z54_210": round(pen_inner + 0.0, 2), "min_gap_to_glass_all": round(pen, 2),
             "tris": sum(len(p.vertices) - 2 for p in ob.data.polygons)}
        if ob.name.startswith("Rib_"):
            sec = {}
            for z in (0.05, 60.07, 120.07, 200.07):
                r = section_extents(vs, es, z)
                sec[str(z)] = {"len": r[0], "thick": r[1], "c": r[2]} if r else None
            d["sections_len_thick_centre"] = sec
        rep[ob.name] = d
    return rep


def build():
    coll = C.collection(COLLECTION)
    for rid in C.RIBS:
        build_rib(rid, coll)
    for name, corner, ang, zend, w0, t0 in FIN_DEFS:
        build_fin(name, corner, ang, zend, w0, t0, coll)
    print("RIBS_MEASURE", json.dumps(measure(coll)))
