"""C03_r4 vs INT R02 room-fit review (read-only measurement). Needs the mesh dump from dump_meshes.py.
usage: python fit_c03_r4.py <C03_r4.npz> <layout.json> <C02 refit_results.csv> <outdir>
Labels: measured = taken from the mesh slice; interpreted = a choice about which part encloses a room; proposed = INT R02 / tower profile."""
import sys, os, csv, json, hashlib, collections, pickle
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fitlib import *

npz, lay, c02csv, outdir = sys.argv[1:5]
P = load_npz(npz)
LAY = json.load(open(lay))
rooms = LAY["rooms"]
C02 = {r["room_id"]: r for r in csv.DictReader(open(c02csv))}
ALLOW = 1.2
SKIN = "Tower_curtainwall_skin"
TOWER_LV = ("L25", "L26")
PODIUM_TIER = {"L00": 1, "L01": 1, "L02": 1, "L03": 2}   # interpretation as in C02: L00-L02 tier-1 wall line, L03 tier-2 wall line
GAP = 22.0                                               # front centre bay half width (podium.py GAP_HALF; confirmed from the slice below)

# ---------------------------------------------------------------- measured constants used by the interpretation
lobby_back = P["Entry_lobby_back_wall"][0]
Y_BACK_FRONT, Y_BACK_REAR = float(lobby_back[:, 1].min()), float(lobby_back[:, 1].max())   # -33.2 / -32.6 measured
Y_LOBBY_GLAZE = float(P["Entry_lobby_glazing"][0][:, 1].min())                               # -44.0 measured (lobby front glazing plane)


# ---------------------------------------------------------------- podium enclosure regions (3 interpretations of the front bay)
_pod_cache = {}


def podium_regions(tier, z):
    key = (tier, round(z, 3))
    if key in _pod_cache: return _pod_cache[key]
    nm = "Podium_Glazing_T%d" % tier
    lines = slice_lines(P, [nm], z)
    polys = list(polygonize(lines))
    assert len(polys) == 1, "expected one C-shaped thin-wall strip, got %d" % len(polys)
    S = polys[0]
    # end caps of the open wall at |x| = GAP: measured y of the two faces
    pts = np.array(S.exterior.coords)
    cap = pts[(np.abs(np.abs(pts[:, 0]) - GAP) < 1e-3) & (pts[:, 1] < -10)]
    assert len(cap) >= 4, "gap end-caps not found at |x|=%.1f" % GAP
    y_out, y_in = float(cap[:, 1].min()), float(cap[:, 1].max())    # outer face / inner (interior) face of the wall line
    bridge = box(-GAP - 1e-3, y_out, GAP + 1e-3, y_in)
    U = unary_union([S, bridge])
    assert U.geom_type == "Polygon" and len(U.interiors) == 1, "closing the gap did not give one enclosed region"
    A = Polygon(U.interiors[0])                                     # (A) chord across the gap at the inner wall face
    B = unary_union([A, box(-GAP, Y_BACK_REAR, GAP, y_in + 1e-6)])  # (B) front bay runs forward to the lobby back wall rear face   [PRIMARY, INTERPRETED]
    Cc = unary_union([A, box(-GAP, Y_LOBBY_GLAZE, GAP, y_in + 1e-6)])  # (C) whole lobby volume up to its front glazing            [INTERPRETED]
    out = {"A": Polygon(A.exterior), "B": Polygon(B.exterior), "C": Polygon(Cc.exterior), "y_out": y_out, "y_in": y_in, "S": S}
    _pod_cache[key] = out
    return out


def govern_label(R, q, tier, variant):
    """Which part owns the nearest boundary point q (a shapely Point on the region outline)."""
    yi = R["y_in"]
    on_side = abs(abs(q.x) - GAP) < 1e-3 and q.y < yi - 1e-3
    on_back = abs(q.y - Y_BACK_REAR) < 1e-3 and abs(q.x) <= GAP + 1e-3 and variant == "B"
    on_glaze = abs(q.y - Y_LOBBY_GLAZE) < 1e-3 and abs(q.x) <= GAP + 1e-3 and variant == "C"
    on_chord = abs(q.y - yi) < 1e-3 and abs(q.x) < GAP - 1e-3 and variant == "A"
    if on_back: return "Entry_lobby_back_wall (INTERPRETED front-bay closure)"
    if on_glaze: return "Entry_lobby_glazing front plane (INTERPRETED)"
    if on_chord: return "front-bay chord at wall line (INTERPRETED)"
    if on_side and variant in ("B", "C"): return "front-bay side line x=+-22 (INTERPRETED, lobby side walls)"
    return "Podium_Glazing_T%d" % tier


# ---------------------------------------------------------------- deck (slab top face) footprint, secondary metric
def deck_region(tier):
    v, t = P["Podium_Slab_T%d" % tier]
    zt = v[:, 2].max(); tri = v[t]
    m = (np.abs(tri[:, :, 2] - zt) < 0.02).all(1)
    polys = [Polygon(tr[:, :2]) for tr in tri[m]]
    polys = [p for p in polys if p.area > 1e-9]
    u = unary_union(polys)
    g = u if u.geom_type == "Polygon" else max(u.geoms, key=lambda p: p.area)
    reg = Polygon(g.exterior)
    lb = P["Entry_lobby_side_walls"][0]
    u2 = unary_union([reg, box(lb[:, 0].min(), Y_LOBBY_GLAZE, lb[:, 0].max(), -25.0)])   # + lobby footprint and the strip joining it to the slab (INTERPRETED)
    return Polygon(u2.exterior)


DECK = {1: deck_region(1), 2: deck_region(2)}

# ---------------------------------------------------------------- intrusion check
zlo = {n: (v[:, 2].min(), v[:, 2].max()) for n, (v, t) in P.items()}
xyb = {n: (v[:, 0].min(), v[:, 1].min(), v[:, 0].max(), v[:, 1].max()) for n, (v, t) in P.items()}
BOUND = {n: boundary_edge_count(v, t) for n, (v, t) in P.items()}   # 0 = watertight solid; >0 = open surface (area fill not meaningful)
_fill = {}


def part_slice(n, z):
    key = (n, round(z, 4))
    if key not in _fill:
        lines = slice_lines(P, [n], z)
        _fill[key] = (lines, filled_even_odd(lines) if lines is not None else Polygon())
    return _fill[key]


def intrusions(rect, z0, z1, skip):
    zs = (z0 + 0.1, 0.5 * (z0 + z1), z1 - 0.1)
    res = {}
    for n in P:
        if n in skip: continue
        lo, hi = zlo[n]
        if hi < z0 - 1e-6 or lo > z1 + 1e-6: continue
        b = xyb[n]
        if b[2] < rect.bounds[0] or b[0] > rect.bounds[2] or b[3] < rect.bounds[1] or b[1] > rect.bounds[3]: continue
        a_max = 0.0; c_max = 0.0; zat = None
        for z in zs:
            if not (lo <= z <= hi): continue
            lines, fill = part_slice(n, z)
            if lines is None: continue
            a = fill.intersection(rect).area if BOUND[n] == 0 else 0.0     # area only for watertight parts; open shells -> cut length only
            c = lines.intersection(rect).length
            if a > a_max + 1e-9 or (a_max == 0 and c > c_max): zat = z
            a_max = max(a_max, a); c_max = max(c_max, c)
        if a_max > 1e-3 or c_max > 1e-2:
            res[n] = (round(a_max, 3), round(c_max, 3), None if zat is None else round(zat, 2), bool(hi <= z0 + 0.5))
    return res


# ---------------------------------------------------------------- main loop
results = []
for r in rooms:
    rid, lv = r["room_id"], r["level_id"]
    rect = box(r["x_m"], r["y_m"], r["x_m"] + r["width_m"], r["y_m"] + r["depth_m"])
    z0 = float(r["z_m"]); z1 = z0 + r["clear_height_m"]
    rec = {"room_id": rid, "level_id": lv, "room_name": r["name"], "z_floor_m": z0, "z_top_m": z1,
           "x_min": r["x_m"], "y_min": r["y_m"], "x_max": r["x_m"] + r["width_m"], "y_max": r["y_m"] + r["depth_m"]}
    if lv in TOWER_LV:
        rec["zone"] = "tower"; rec["governing_part"] = SKIN
        rec["basis"] = "measured: skin slice; governing-part assignment per C02 interpretation (L25/L26 -> curtainwall skin)"
        ms = {}
        for tag, z in (("floor", z0 + 0.01), ("top", z1 - 0.01)):
            reg = outer_region(slice_lines(P, [SKIN], z))
            ms[tag] = signed_margin(rect, reg)
        worst_tag = min(ms, key=lambda k: ms[k][0])
        m, where, pt = ms[worst_tag]
        # extra, beyond the brief: dense sweep through the clear height (every 0.15 m)
        dense = []
        zz = z0 + 0.01
        while zz < z1 - 0.01 + 1e-9:
            reg = outer_region(slice_lines(P, [SKIN], zz)); dense.append((signed_margin(rect, reg)[0], zz)); zz += 0.15
        dmin = min(dense)
        rec.update({"worst_margin_m": m, "status": classify(m, ALLOW), "worst_at_slice": worst_tag, "worst_where": where, "worst_point_xy": pt,
                    "margin_floor_slice_m": ms["floor"][0], "margin_top_slice_m": ms["top"][0], "margin_dense_min_m": dmin[0], "dense_min_at_z": round(dmin[1], 2)})
        if m < 0:
            rec["status"] = "OUTSIDE_SKIN"; rec["shortfall_m"] = -m
        skip = {SKIN}
    else:
        tier = PODIUM_TIER[lv]
        rec["zone"] = "podium"
        zmax = zlo["Podium_Glazing_T%d" % tier][1]
        zs = [z0 + 0.5, min(z1 - 0.01, zmax - 0.3)]
        var = {}
        for vname in ("A", "B", "C"):
            cand = []
            for z in zs:
                R = podium_regions(tier, z)
                cand.append(signed_margin(rect, R[vname]))
            var[vname] = min(cand, key=lambda c: c[0])
        m, where, pt = var["B"]
        R = podium_regions(tier, zs[0])
        q = nearest_points(R["B"].exterior, Point(pt))[0]
        rec["governing_part"] = govern_label(R, q, tier, "B")
        rec["basis"] = ("measured wall slice (Podium_Glazing_T%d, outline identical at all sampled z); front bay |x|<=22 closed per INTERPRETED variant B "
                        "(lobby back wall rear face y=%.2f); tier assignment per C02 interpretation" % (tier, Y_BACK_REAR))
        pr = {k: var[k][0] for k in "ABC"}
        dm = signed_margin(rect, DECK[tier])[0]
        in_bay = bool(rect.bounds[0] < GAP and rect.bounds[2] > -GAP and rect.bounds[1] < R["y_in"])
        rec.update({"worst_margin_m": m, "worst_where": where, "worst_point_xy": pt, "margin_A_chord_m": pr["A"], "margin_B_backwall_m": pr["B"], "margin_C_lobbyglass_m": pr["C"],
                    "status_A": classify(pr["A"], ALLOW), "status_B": classify(pr["B"], ALLOW), "status_C": classify(pr["C"], ALLOW),
                    "deck_margin_m": dm, "front_bay_room": in_bay})
        st = classify(m, ALLOW)
        if st == "OUTSIDE":
            st = "OUTSIDE_WALL_AND_DECK" if dm < 0 else "OUTSIDE_WALL_INSIDE_DECK"
        rec["status"] = st
        if m < 0: rec["shortfall_m"] = -m
        skip = {"Podium_Glazing_T%d" % tier}
        c = C02.get(rid)
        if c: rec.update({"c02_margin_m": float(c["my_wall_margin_m"]), "c02_status": c["my_status"]})
    intr = intrusions(rect, z0, z1, skip)
    rec["intruding_parts"] = {k: {"max_area_m2": v[0], "max_cut_len_m": v[1], "at_z": v[2]} for k, v in intr.items() if not v[3]}
    rec["floor_level_parts"] = {k: {"max_area_m2": v[0], "max_cut_len_m": v[1]} for k, v in intr.items() if v[3]}
    results.append(rec)

os.makedirs(outdir, exist_ok=True)
pickle.dump(results, open(os.path.join(outdir, "scratch", "results.pkl"), "wb"))
cnt = lambda lvs, key="status": dict(collections.Counter(x[key] for x in results if x["level_id"] in lvs))
print("TOWER L25/L26:", cnt(TOWER_LV))
print("PODIUM L00-L03 (primary B):", cnt(("L00", "L01", "L02", "L03")))
for v in "ABC":
    print("  podium variant", v, dict(collections.Counter(x["status_" + v] for x in results if x["zone"] == "podium")))
