"""Option tables for the tower glass profile (options only, not decisions). Uses sweep_tower.worst_margin (validated vs the C03_r4 mesh)."""
import sys, os, json, numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sweep_tower import worst_margin, change_cost, CUR
out = {}
def bis(f, lo, hi, n=40):
    # smallest x in [lo,hi] with f(x)>=0 (f monotone increasing); None if f(hi)<0
    if f(hi) < 0: return None
    for _ in range(n):
        m = (lo + hi) / 2
        if f(m) >= 0: hi = m
        else: lo = m
    return hi
for T in (0.0, 1.2):
    t = {}
    # (c) glass held at the R06 base 68x54 (no taper at all, K irrelevant): smallest plan exponent N
    t["untapered_68x54_min_N"] = bis(lambda N: worst_margin(68, 54, 1.8, N) - T, 2.5, 60)
    # (a) keep top 42x32; plan exponent N; the largest K that still works (K smaller = glass stays wide longer)
    a = {}
    for N in (2.5, 4, 6, 8, 10, 16, 30):
        K = bis(lambda k: -(worst_margin(42, 32, 0 + k, N) - T), 0.01, 3.0)   # find where margin crosses T going down with K
        # worst_margin decreases with K: want largest K with margin>=T
        lo, hi = 0.01, 6.0
        if worst_margin(42, 32, lo, N) < T: a[str(N)] = None; continue
        for _ in range(40):
            m = (lo + hi) / 2
            if worst_margin(42, 32, m, N) >= T: lo = m
            else: hi = m
        a[str(N)] = round(lo, 3)
    t["keep_top_42x32_max_K_by_N"] = a
    # (b) keep K=1.8; scale top (W,D) with the current 42:32 aspect; minimal scale by N
    b = {}
    for N in (2.5, 4, 6, 8, 10, 16, 30):
        s = bis(lambda s: worst_margin(42 * s, 32 * s, 1.8, N) - T, 1.0, 4.0)
        b[str(N)] = None if s is None else {"W": round(42 * s, 2), "D": round(32 * s, 2)}
    t["keep_K_1.8_min_top_by_N"] = b
    # (d) N=2.5 fixed (only env knobs): any feasible top/K? (K,W,D free; scaled with the 68:54 base aspect)
    d = {}
    for K in (0.5, 1.0, 1.8, 3.0, 5.0, 8.0):
        s = bis(lambda s: worst_margin(68 * s, 54 * s, K, 2.5) - T, 0.3, 3.0)
        d[str(K)] = None if s is None else {"W": round(68 * s, 2), "D": round(54 * s, 2)}
    t["N2.5_env_knobs_only_top_with_68to54_aspect_by_K"] = d
    out[str(T)] = t
json.dump(out, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "sweep_options.json"), "w"), indent=1)
print(json.dumps(out, indent=1))
