"""Sweep of the PROPOSED tower glass profile (CL_TOP_W, CL_TOP_D, CL_FLARE_K and, beyond the env knobs, tower.py SUPER_N)
against the 32 INT R02 L25/L26 rooms. Options only; nothing here changes a model file. Vectorised re-creation of
Tower_curtainwall_skin (skin_model.py), validated against the C03_r4 mesh (max room-margin difference 6e-5 m)."""
import sys, os, json, itertools, numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import skin_model as S

ROOMS = json.load(open("C:/q2/layout.json"))["rooms"]
TOWER = [r for r in ROOMS if r["level_id"] in ("L25", "L26")]
ZPTS = {}   # z -> unique corner points
for r in TOWER:
    z0 = r["z_m"]; z1 = z0 + r["clear_height_m"]
    cs = [(r["x_m"], r["y_m"]), (r["x_m"] + r["width_m"], r["y_m"]), (r["x_m"] + r["width_m"], r["y_m"] + r["depth_m"]), (r["x_m"], r["y_m"] + r["depth_m"])]
    for z in (z0 + 0.01, z1 - 0.01):
        ZPTS.setdefault(round(z, 3), set()).update(cs)
ZPTS = {z: np.array(sorted(p)) for z, p in ZPTS.items()}
LV = np.array(S.levels())
TH = -np.pi / 2 + 2 * np.pi * np.arange(S.NPTS) / S.NPTS
C_, S_ = np.cos(TH), np.sin(TH)


def ring_np(z, W, D, K, N):
    t = min(max((z - S.Z0) / (S.Z1 - S.Z0), 0.0), 1.0)
    f = (1 - t) ** K
    hx = W / 2 + (S.BASE[0] / 2 - W / 2) * f; hy = D / 2 + (S.BASE[1] / 2 - D / 2) * f
    XN = 2 / N
    x = hx * np.sign(C_) * np.abs(C_) ** XN; y = hy * np.sign(S_) * np.abs(S_) ** XN
    gx = N * np.abs(x / hx) ** (N - 1) * np.sign(x) / hx; gy = N * np.abs(y / hy) ** (N - 1) * np.sign(y) / hy
    g = np.hypot(gx, gy)
    fr = ((z - S.Z0) / S.STOREY) % 1.0
    if abs(fr - 1.0) < 1e-6: fr = 0.0
    b = S.BULGE * np.sin(np.pi * fr)
    return np.c_[x + gx / g * b, y + gy / g * b]


def section_np(z, W, D, K, N):
    k = int(np.clip((z - S.Z0) // (LV[1] - LV[0]), 0, len(LV) - 2))
    A = ring_np(LV[k], W, D, K, N); B = ring_np(LV[k + 1], W, D, K, N)
    u = (z - LV[k]) / (LV[k + 1] - LV[k])
    return A + u * (B - A)


def sdist(poly, pts):
    """Signed distance of points to a convex polygon outline (>0 inside)."""
    a = poly; b = np.roll(poly, -1, axis=0); ab = b - a; L2 = (ab ** 2).sum(1)
    ap = pts[:, None, :] - a[None]
    t = np.clip((ap * ab[None]).sum(2) / L2[None], 0, 1)
    q = a[None] + t[..., None] * ab[None]
    d = np.sqrt(((pts[:, None, :] - q) ** 2).sum(2)).min(1)
    cr = ab[None, :, 0] * ap[..., 1] - ab[None, :, 1] * ap[..., 0]    # polygon is CCW (th increasing) -> inside when all cross >= 0
    inside = (cr >= -1e-12).all(1)
    return np.where(inside, d, -d)


def worst_margin(W, D, K, N):
    m = 1e9
    for z, pts in ZPTS.items():
        m = min(m, sdist(section_np(z, W, D, K, N), pts).min())
    return m


CUR = (42.0, 32.0, 1.8, 2.5)
ZS = np.arange(54, 216.01, 4.5)


def half_ext(z, W, D, K):
    return S.half_extents(z, W, D, K)


def change_cost(W, D, K):
    """Mean and max absolute change of glass half-width / half-depth along the height 54..216 relative to the current profile (m)."""
    dx = []; dy = []
    for z in ZS:
        a = half_ext(z, W, D, K); b = half_ext(z, CUR[0], CUR[1], CUR[2])
        dx.append(abs(a[0] - b[0])); dy.append(abs(a[1] - b[1]))
    dx = np.array(dx); dy = np.array(dy)
    return float(((dx + dy) / 2).mean()), float(max(dx.max(), dy.max()))


if __name__ == "__main__":
    out = {}
    print("baseline worst margin %.3f m" % worst_margin(*CUR))
    for T in (0.0, 1.2):
        best = {}
        for N in (2.5, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 16.0):
            cand = None
            for K in np.round(np.arange(0.1, 6.01, 0.2), 2):
                for W in np.arange(30, 100.01, 2.0):
                    if worst_margin(W, 90.0, K, N) < T - 1e-9: continue          # even D=90 is not enough at this W
                    lo, hi = 20.0, 90.0                                          # margin is monotone in D: bisect the smallest D that works
                    for _ in range(14):
                        mid = 0.5 * (lo + hi)
                        if worst_margin(W, mid, K, N) >= T - 1e-9: hi = mid
                        else: lo = mid
                    D = round(hi + 0.005, 2)
                    c = change_cost(W, D, K)
                    if cand is None or c[0] < cand[0]:
                        cand = (c[0], c[1], W, D, K)
            best[N] = cand
            print("target %.1f  N=%.1f ->" % (T, N), None if cand is None else "mean_dchange %.2f m, max %.2f m, top %gx%g, K=%.1f" % (cand[0], cand[1], cand[2], cand[3], cand[4]), flush=True)
        out[str(T)] = {str(N): (None if c is None else {"mean_change_m": c[0], "max_change_m": c[1], "W": c[2], "D": c[3], "K": c[4]}) for N, c in best.items()}
    json.dump(out, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "sweep_grid_raw.json"), "w"), indent=1)
