"""Analytic re-creation of Tower_curtainwall_skin (tower.py + cl_common.tower_half_extents) for parameter sweeps.
Same maths as the module: superellipse |x/hx|^N+|y/hy|^N=1 with N=SUPER_N, 96 plan points, 4 ring levels per 4.5 m storey,
sin bulge 0.22 m per storey. Verified against the dumped C03_r4 mesh (see verify_skin_model in sweep_tower.py)."""
import math, numpy as np

Z0, Z1, STOREY, SUB, NPTS, BULGE = 54.0, 216.0, 4.5, 4, 96, 0.22
BASE = (68.0, 54.0)


def half_extents(z, top_w, top_d, K):
    t = min(max((z - Z0) / (Z1 - Z0), 0.0), 1.0)
    f = (1.0 - t) ** K
    return top_w / 2 + (BASE[0] / 2 - top_w / 2) * f, top_d / 2 + (BASE[1] / 2 - top_d / 2) * f


def bul(z):
    f = ((z - Z0) / STOREY) % 1.0
    if abs(f - 1.0) < 1e-6: f = 0.0
    return BULGE * math.sin(math.pi * f)


def ring(z, top_w, top_d, K, N):
    hx, hy = half_extents(z, top_w, top_d, K)
    XN = 2 / N
    pts = []
    for i in range(NPTS):
        th = -math.pi / 2 + 2 * math.pi * i / NPTS
        c, s = math.cos(th), math.sin(th)
        sg = lambda v: 1.0 if v >= 0 else -1.0
        x = hx * sg(c) * abs(c) ** XN
        y = hy * sg(s) * abs(s) ** XN
        gx = N * abs(x / hx) ** (N - 1) * sg(x) / hx
        gy = N * abs(y / hy) ** (N - 1) * sg(y) / hy
        g = math.hypot(gx, gy)
        b = bul(z)
        pts.append((x + gx / g * b, y + gy / g * b))
    return pts


def levels():
    n = int(round((Z1 - Z0) / STOREY)) * SUB
    return [Z0 + (Z1 - Z0) * k / n for k in range(n + 1)]


def section_polygon(z, top_w, top_d, K, N):
    """Cross-section outline at height z of the lofted skin (rings linearly joined, quad split into two triangles)."""
    from shapely.geometry import Polygon
    lv = levels()
    k = max(0, min(len(lv) - 2, int((z - Z0) / (lv[1] - lv[0]))))
    za, zb = lv[k], lv[k + 1]
    A = np.array(ring(za, top_w, top_d, K, N)); B = np.array(ring(zb, top_w, top_d, K, N))
    u = (z - za) / (zb - za)
    return Polygon(A + u * (B - A))
