"""Regression check: reproduce the C02 room-fit numbers with the NEW engine (fitlib.py), independent of refit_c02.py.
usage: python regress_c02.py <C02.glb> <layout.json> <refit_results.csv> <published C02_FIT_COVERAGE.csv> <out.csv>
C02 interpretation (published, not derived here): L00-L02 -> Podium_wall_1 sliced at floor+0.5; L03 -> Podium_wall_2;
L25/L26 -> Tower_curtainwall_skin at floor+0.01 and ceiling-0.01 (worse of the two); deck margin vs Deck_n_top bbox."""
import sys, csv, json, collections
sys.path.insert(0, __import__("os").path.dirname(__file__))
from fitlib import *
glb, lay, mine_csv, pub_csv, out = sys.argv[1:6]
P = load_glb_source_frame(glb)
rooms = json.load(open(lay))["rooms"]
old = {r["room_id"]: r for r in csv.DictReader(open(mine_csv))}
pub = {r["room_id"]: r for r in csv.DictReader(open(pub_csv, encoding="utf-8"))}
WALL = {"L00": "Podium_wall_1", "L01": "Podium_wall_1", "L02": "Podium_wall_1", "L03": "Podium_wall_2"}
DECK = {"L00": "Deck_1_top_18m", "L01": "Deck_1_top_18m", "L02": "Deck_1_top_18m", "L03": "Deck_2_top_36m"}
rows = []
for r in rooms:
    rect = box(r["x_m"], r["y_m"], r["x_m"] + r["width_m"], r["y_m"] + r["depth_m"])
    z0 = r["z_m"]; z1 = z0 + r["clear_height_m"]; lv = r["level_id"]
    if lv in WALL:
        nm = WALL[lv]; zmax = P[nm][0][:, 2].max(); zs = [min(z0 + 0.5, zmax - 0.5)]
    else:
        nm = "Tower_curtainwall_skin"; zs = [z0 + 0.01, z1 - 0.01]
    ms = []
    for z in zs:
        reg = outer_region(slice_lines(P, [nm], z))
        ms.append(signed_margin(rect, reg)[0])
    m = min(ms)
    deckm = None
    if lv in DECK:
        dv = P[DECK[lv]][0]
        deckm = min(rect.bounds[0] - dv[:, 0].min(), dv[:, 0].max() - rect.bounds[2], rect.bounds[1] - dv[:, 1].min(), dv[:, 1].max() - rect.bounds[3])
    if m >= 1.2 - 1e-3: st = "FITS"
    elif m >= 0: st = "INSIDE_BELOW_ALLOWANCE"
    else: st = ("OUTSIDE_WALL_AND_DECK" if (deckm is not None and deckm < 0) else ("OUTSIDE_WALL_INSIDE_DECK" if deckm is not None else "OUTSIDE_SKIN"))
    rows.append((r["room_id"], lv, m, deckm, st))
cnt = collections.Counter(x[4] for x in rows)
print("new-engine C02 statuses:", dict(cnt))
d_old = [abs(x[2] - float(old[x[0]]["my_wall_margin_m"])) for x in rows]
d_pub = [abs(x[2] - float(pub[x[0]]["wall_margin_m"])) for x in rows if pub[x[0]]["wall_margin_m"]]
dis_old = [x[0] for x in rows if x[4] != old[x[0]]["my_status"]]
dis_pub = [x[0] for x in rows if x[4] != pub[x[0]]["status"]]
print("vs refit_c02.py: max margin diff %.5f m, status disagreements %d %s" % (max(d_old), len(dis_old), dis_old))
print("vs published CSV: max margin diff %.5f m (n=%d), status disagreements %d %s" % (max(d_pub), len(d_pub), len(dis_pub), dis_pub))
for x in rows:
    if x[4] != "FITS": print("  ", x)
with open(out, "w", newline="") as f:
    w = csv.writer(f); w.writerow(["room_id", "level_id", "new_engine_margin_m", "deck_margin_m", "new_engine_status", "refit_c02_margin_m", "refit_c02_status", "published_margin_m", "published_status"])
    for x in rows:
        w.writerow([x[0], x[1], round(x[2], 4), "" if x[3] is None else round(x[3], 4), x[4], old[x[0]]["my_wall_margin_m"], old[x[0]]["my_status"], pub[x[0]]["wall_margin_m"], pub[x[0]]["status"]])
json.dump({"statuses": dict(cnt), "max_margin_diff_vs_refit_c02_m": max(d_old), "max_margin_diff_vs_published_m": max(d_pub),
           "status_disagreements_vs_refit_c02": dis_old, "status_disagreements_vs_published": dis_pub}, open(out.replace(".csv", ".json"), "w"), indent=1)
