"""Same-model plan and vertical sections (PNG + SVG), model revision C03_r4 on every sheet.
usage: python sheets_c03_r4.py <outdir> <C03_r4.npz>"""
import sys, os, json, pickle
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fitlib import *
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Polygon as MPoly

outdir, npz = sys.argv[1:3]
P = load_npz(npz)
R = pickle.load(open(os.path.join(outdir, "scratch", "results.pkl"), "rb"))
SD = os.path.join(outdir, "sheets"); os.makedirs(SD, exist_ok=True)
REV = "Model revision C03_r4 (SHA-256 f24ebb01...610dc4)  |  INT R02 layout (SHA-256 aa14f38b...42ff)  |  measured geometry; allowance 1.2 m = proposed"
COL = {"FITS": "#2e9d4f", "INSIDE_BELOW_ALLOWANCE": "#e0a21b", "OUTSIDE_SKIN": "#d33a2c", "OUTSIDE_WALL_AND_DECK": "#d33a2c", "OUTSIDE_WALL_INSIDE_DECK": "#e8702a"}


def save(fig, name):
    fig.savefig(os.path.join(SD, name + ".png"), dpi=140, bbox_inches="tight")
    fig.savefig(os.path.join(SD, name + ".svg"), bbox_inches="tight")
    plt.close(fig)


def scalebar(ax, x, y, L=10.0, vertical=False):
    if vertical:
        ax.plot([x, x], [y, y + L], "k-", lw=3, solid_capstyle="butt"); ax.text(x + 0.6, y + L / 2, "%g m" % L, fontsize=7, va="center")
    else:
        ax.plot([x, x + L], [y, y], "k-", lw=3, solid_capstyle="butt"); ax.text(x + L / 2, y - 1.2, "%g m" % L, fontsize=7, ha="center", va="top")


def draw_lines(ax, lines, **kw):
    if lines is None: return
    gs = list(lines.geoms) if hasattr(lines, "geoms") else [lines]
    for g in gs:
        x, y = g.xy; ax.plot(x, y, **kw)


def rect_patch(ax, r, label=True, fs=6.5, margin=True):
    c = COL[r["status"]]
    ax.add_patch(Rectangle((r["x_min"], r["y_min"]), r["x_max"] - r["x_min"], r["y_max"] - r["y_min"], fc=c, ec="k", lw=0.6, alpha=0.45, zorder=5))
    if label:
        t = r["room_id"].split("-")[1]
        if margin: t += "\n%+.1f" % r["worst_margin_m"]
        ax.text((r["x_min"] + r["x_max"]) / 2, (r["y_min"] + r["y_max"]) / 2, t, fontsize=fs, ha="center", va="center", zorder=6, clip_on=True)


def legend(ax, loc="lower left"):
    from matplotlib.lines import Line2D
    h = [Rectangle((0, 0), 1, 1, fc=COL[k], alpha=0.45, ec="k", lw=0.6) for k in ("FITS", "INSIDE_BELOW_ALLOWANCE", "OUTSIDE_SKIN")]
    ax.legend(h, ["FITS (>= 1.2 m)", "INSIDE_BELOW_ALLOWANCE (0-1.2 m)", "OUTSIDE (< 0 m)"], fontsize=6.5, loc=loc, framealpha=0.9)


# ------------------------------------------------------------------ sheet 1: tower plans z=126.0 and z=130.5
OTHER = {"Tower_storey_bands": ("#c9a13b", 0.5), "Tower_mullions": ("#c9a13b", 0.4), "Tower_front_channel": ("#e8902a", 0.8), "Tower_front_lattice": ("#e8902a", 0.4),
         "Tower_rear_pod": ("#e8902a", 0.8), "Tower_rear_pod_gold": ("#e8902a", 0.4)}
fig, axs = plt.subplots(1, 2, figsize=(16, 8.4))
for ax, (lv, z) in zip(axs, (("L25", 126.0), ("L26", 130.5))):
    rooms = [r for r in R if r["level_id"] == lv]
    zt = rooms[0]["z_top_m"] - 0.01
    for n, (c, lw) in OTHER.items():
        draw_lines(ax, slice_lines(P, [n], z + 0.01), color=c, lw=lw, zorder=2)
    for n in ("Rib_R1", "Rib_R2", "Rib_R3", "Rib_R4", "Rib_R5", "Rib_R6"):
        draw_lines(ax, slice_lines(P, [n], z + 0.01), color="#777777", lw=1.0, zorder=2)
    draw_lines(ax, slice_lines(P, ["Tower_curtainwall_skin"], z + 0.01), color="#1f5fa8", lw=1.8, zorder=4)
    draw_lines(ax, slice_lines(P, ["Tower_curtainwall_skin"], zt), color="#1f5fa8", lw=1.0, ls="--", zorder=4)
    for r in rooms: rect_patch(ax, r)
    sk = outer_region(slice_lines(P, ["Tower_curtainwall_skin"], z + 0.01)).bounds
    ax.set_xlim(-42, 42); ax.set_ylim(-34, 34); ax.set_aspect("equal"); ax.grid(True, lw=0.3, alpha=0.5)
    ax.set_xlabel("x (m), + = right"); ax.set_ylabel("y (m), - = front")
    ax.set_title("%s plan section at z = %.1f m (floor)\nskin %.1f x %.1f m (solid = floor, dashed = ceiling z=%.2f); block %.0f x %.0f m" % (
        lv, z, sk[2] - sk[0], sk[3] - sk[1], zt, max(r["x_max"] for r in rooms) - min(r["x_min"] for r in rooms), max(r["y_max"] for r in rooms) - min(r["y_min"] for r in rooms)), fontsize=9)
    scalebar(ax, -40, -31)
    ax.annotate("FRONT (-Y)", (0, -33), ha="center", fontsize=7); ax.annotate("REAR (+Y)", (0, 32.5), ha="center", fontsize=7)
    legend(ax, "upper left")
    ax.text(41, -33, "grey = ribs R1-R6, gold = bands/mullions (outside glass),\norange = channel / rear pod (outside glass);\nlabels: room no. and worst margin (m)", fontsize=6, ha="right", va="bottom")
fig.suptitle("C03_r4 tower plan sections vs INT R02 rooms (measured; margins in metres, + inside / - outside the skin)", fontsize=11)
fig.text(0.5, 0.02, REV, ha="center", fontsize=7)
save(fig, "01_tower_plan_L25_L26")

# ------------------------------------------------------------------ sheet 2: vertical sections x=0 and y=0
def vsec(ax, axis, zlim, full):
    names = [n for n in P if n.startswith(("Tower_", "Rib_", "Fin_", "Crown_petal", "Crown_Petal", "Entry_arch_blade"))]
    for n in names:
        l = slice_lines(P, [n], 0.0, axis=axis, tag="v%d" % axis)
        if l is None: continue
        c = "#1f5fa8" if n == "Tower_curtainwall_skin" else "#c9a13b" if n in ("Tower_storey_bands", "Tower_mullions") else "#e8902a" if n.startswith(("Tower_front", "Tower_rear")) else "#888888"
        lw = 1.6 if n == "Tower_curtainwall_skin" else 0.5
        draw_lines(ax, l, color=c, lw=lw, zorder=3 if n == "Tower_curtainwall_skin" else 2)
    # rooms intersecting the plane
    for r in R:
        if r["level_id"] not in ("L25", "L26"): continue
        lo, hi = (r["x_min"], r["x_max"]) if axis == 0 else (r["y_min"], r["y_max"])   # axis=0 -> plane x=0 spans y ; axis=1 -> plane y=0 spans x
        pl_lo, pl_hi = (r["x_min"], r["x_max"]) if axis == 0 else (r["y_min"], r["y_max"])
        if not (pl_lo <= 0 <= pl_hi): continue
        a, b = (r["y_min"], r["y_max"]) if axis == 0 else (r["x_min"], r["x_max"])
        ax.add_patch(Rectangle((a, r["z_floor_m"]), b - a, r["z_top_m"] - r["z_floor_m"], fc=COL[r["status"]], ec="k", lw=0.6, alpha=0.5, zorder=5))
        if not full:
            ax.text((a + b) / 2, (r["z_floor_m"] + r["z_top_m"]) / 2, "%s\n%+.1f" % (r["room_id"].split("-")[0] + "-" + r["room_id"].split("-")[1][2:], r["worst_margin_m"]), fontsize=6, ha="center", va="center", zorder=6, clip_on=True)
    ax.grid(True, lw=0.3, alpha=0.5)
    ax.set_aspect("equal" if full else "auto")


for axis, nm, hl in ((0, "x = 0", "y (m), - = front"), (1, "y = 0", "x (m), + = right")):
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(16, 8.5), gridspec_kw={"width_ratios": [1, 1.25]})
    vsec(a1, axis, (0, 245), True)
    a1.set_xlim(-85, 85); a1.set_ylim(-5, 245)
    a1.add_patch(Rectangle((-85, 126), 170, 8.1, fc="none", ec="k", ls=":", lw=0.8))
    a1.set_title("Full-height section at %s (grey = ribs/fins/crown, orange = channel/pod; zoom box dotted)" % nm, fontsize=8)
    a1.set_xlabel(hl); a1.set_ylabel("z (m)"); scalebar(a1, -80, 5, 20, vertical=True)
    vsec(a2, axis, (118, 142), False)
    a2.set_xlim(-32, 32); a2.set_ylim(120, 140)
    a2.set_title("Zoom L25 (z 126-129.6) / L26 (z 130.5-134.1): skin vs room blocks cut by the plane (vertical scale exaggerated)", fontsize=8)
    a2.set_xlabel(hl); a2.set_ylabel("z (m)"); scalebar(a2, -30, 121.5, 10)
    legend(a2, "upper right")
    fig.suptitle("C03_r4 vertical section at %s through L25/L26 (measured)" % nm, fontsize=11)
    fig.text(0.5, 0.02, REV, ha="center", fontsize=7)
    save(fig, "02_vertical_section_%s" % nm.replace(" ", "").replace("=", ""))

# ------------------------------------------------------------------ sheet 3: podium plans L00-L03
Y_BACK_REAR = float(P["Entry_lobby_back_wall"][0][:, 1].max()); Y_GL = float(P["Entry_lobby_glazing"][0][:, 1].min())
PT = {"L00": 1, "L01": 1, "L02": 1, "L03": 2}
ENTRY = [n for n in P if n.startswith("Entry_") and "basin" not in n and "dome" not in n and "canopy" not in n and "forecourt" not in n and "roof" not in n]
for lv in ("L00", "L01", "L02", "L03"):
    rooms = [r for r in R if r["level_id"] == lv]
    z0 = rooms[0]["z_floor_m"]; z = z0 + 0.5; tier = PT[lv]
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(17, 7.6), gridspec_kw={"width_ratios": [1.5, 1]})
    for ax, win in ((a1, (-80, 80, -62, 62)), (a2, (-48, 48, -58, -8))):
        for n in ("Podium_Slab_T%d" % tier,):
            v, t = P[n]; zt = v[:, 2].max(); tri = v[t]
            top = (np.abs(tri[:, :, 2] - zt) < 0.02).all(1)
            u = unary_union([Polygon(q[:, :2]) for q in tri[top] if Polygon(q[:, :2]).area > 1e-9])
            g = u if u.geom_type == "Polygon" else max(u.geoms, key=lambda p: p.area)
            ax.plot(*Polygon(g.exterior).exterior.xy, color="#999999", lw=0.8, ls="-.", zorder=1)
        for n in ["Podium_Piers_T%d" % tier, "Podium_Mullions_T%d" % tier] + [q for q in P if q.startswith(("Rib_", "Fin_"))] + ENTRY:
            draw_lines(ax, slice_lines(P, [n], z), color="#8a6d3b" if n.startswith("Podium") else "#777777" if n.startswith(("Rib", "Fin")) else "#2255aa", lw=0.5, zorder=2)
        draw_lines(ax, slice_lines(P, ["Podium_Glazing_T%d" % tier], z), color="k", lw=1.2, zorder=4)
        # interpreted front-bay closure B (dashed) and C (dotted)
        ax.plot([-22, 22], [Y_BACK_REAR, Y_BACK_REAR], color="#c2185b", lw=1.4, ls="--", zorder=4)
        ax.plot([-22, -22], [Y_BACK_REAR, -25.15], color="#c2185b", lw=1.4, ls="--", zorder=4); ax.plot([22, 22], [Y_BACK_REAR, -25.15], color="#c2185b", lw=1.4, ls="--", zorder=4)
        ax.plot([-22, 22], [Y_GL, Y_GL], color="#c2185b", lw=1.0, ls=":", zorder=4)
        for r in rooms: rect_patch(ax, r, fs=6 if ax is a1 else 7.5)
        ax.set_xlim(win[0], win[1]); ax.set_ylim(win[2], win[3]); ax.set_aspect("equal"); ax.grid(True, lw=0.3, alpha=0.5)
        ax.set_xlabel("x (m)"); ax.set_ylabel("y (m), - = front")
    scalebar(a1, -76, -58, 20); scalebar(a2, -45, -56, 10)
    a1.set_title("%s plan section at z = %.1f m (floor+0.5)\nblack = Podium_Glazing_T%d (governing wall), brown = piers/mullions, grey = ribs/fins, blue = Entry parts" % (lv, z, tier), fontsize=8)
    a2.set_title("Front bay zoom. Pink dashed = INTERPRETED closure B\n(lobby back wall rear face y=%.1f, x=+-22); dotted = variant C (lobby glazing y=%.1f)" % (Y_BACK_REAR, Y_GL), fontsize=8)
    legend(a1, "upper left")
    fig.suptitle("C03_r4 podium plan %s vs INT R02 rooms; label = room no. and worst margin (m) against closure B (measured wall, INTERPRETED front bay)" % lv, fontsize=10)
    fig.text(0.5, 0.0, REV, ha="center", fontsize=7)
    save(fig, "03_podium_plan_%s" % lv)
print("sheets written to", SD, sorted(os.listdir(SD)))
