import json,csv,math,re,collections,itertools,sys
import numpy as np
src=open("C:/q2/refit.py").read().split("L=json.load")[0]
exec(src)   # loads GLB, mesh dict, slice_segs, zone (read-only copy of helper code)
from shapely.geometry import box,Point,LineString,Polygon
from shapely.ops import unary_union,polygonize
OUT="C:/q2/out/B_vertical/"
D=json.load(open("C:/q2/layout.json"))
rooms=D["rooms"];doors=D["doors"]
R={r["room_id"]:r for r in rooms}
def rect(r): return box(r["x_m"],r["y_m"],r["x_m"]+r["width_m"],r["y_m"]+r["depth_m"])
F=[]
def add(fid,topic,label,item,value,unit="",note=""):
    F.append(dict(id=fid,topic=topic,label=label,item=item,value=value,unit=unit,note=note))
def wcsv(name,rows):
    with open(OUT+name,"w",newline="") as f:
        keys=[]
        for r in rows:
            for k in r:
                if k not in keys: keys.append(k)
        w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(rows)
LEVELS=["L00","L01","L02","L03","L25","L26"]
Z={}
for r in rooms: Z[r["level_id"]]=r["z_m"]
pat=re.compile(r"lift|stair|core|shaft|service|elev|riser|reserve|vestibule|mep",re.I)
CORE_IDS=("090","091","092","093","094")
core=[r for r in rooms if r["room_id"][-3:] in CORE_IDS]
other_service=[r for r in rooms if r not in core and (pat.search(r["name"]) or r["access"] in("core","service"))]
wcsv("core_footprints.csv",[dict(room_id=r["room_id"],level=r["level_id"],z_m=r["z_m"],name=r["name"],x_m=r["x_m"],y_m=r["y_m"],width_m=r["width_m"],depth_m=r["depth_m"],x_max=r["x_m"]+r["width_m"],y_max=r["y_m"]+r["depth_m"],area_m2=r["width_m"]*r["depth_m"],clear_height_m=r["clear_height_m"],access=r["access"],label="proposed (dimension_status=%s)"%r["dimension_status"]) for r in sorted(core,key=lambda r:(LEVELS.index(r["level_id"]),r["room_id"]))])
wcsv("other_service_rooms_not_vertical.csv",[dict(room_id=r["room_id"],level=r["level_id"],name=r["name"],x_m=r["x_m"],y_m=r["y_m"],width_m=r["width_m"],depth_m=r["depth_m"],access=r["access"],label="proposed; keyword/access match only, not a lift/stair/shaft") for r in other_service])
for lv in LEVELS:
    c=[r for r in core if r["level_id"]==lv]
    stairs=[r for r in c if "stair" in r["name"].lower()]
    lifts=[r for r in c if "passenger lift" in r["name"].lower()]
    svc=[r for r in c if "service lift" in r["name"].lower()]
    lift_doors=[d for d in doors if d["level_id"]==lv and d["type"]=="lift" and d["to_room"].endswith("092")]
    add("B2.count.%s"%lv,"count","proposed","%s stairs / passenger-lift door records / service reserve rooms"%lv,
        "stairs=%d (req 2); passenger lift door records=%d in %d shaft room (req 3 lifts); service reserve rooms=%d (req 1)"%(len(stairs),len(lift_doors),len(lifts),len(svc)),"",
        "passenger lifts are ONE room 'Three passenger lift shafts' 12x4.8 m; 3 is inferred from name + 3 lift door records (x=-4,0,4) + notes + brief '4 x 4.8 m planning cells'")
types={"Stair A":"090","Stair B":"091","Passenger lifts":"092","Service lift/MEP reserve":"093","Service vestibule":"094"}
cont=[]
def rr(lv,s): return R["%s-RM%s"%(lv,s)]
pairs=[("L00","L01"),("L01","L02"),("L02","L03"),("L25","L26"),("L03","L25")]
for tn,s in types.items():
    for a,b in pairs:
        ra,rb=rr(a,s),rr(b,s);pa,pb=rect(ra),rect(rb)
        inter=pa.intersection(pb).area;uni=pa.union(pb).area
        lab="measured (arithmetic on proposed layout)" if (a,b)!=("L03","L25") else "interpreted (endpoints identical; 108 m between has no layout)"
        cont.append(dict(type=tn,lower=a,upper=b,rise_m=Z[b]-Z[a],dx=rb["x_m"]-ra["x_m"],dy=rb["y_m"]-ra["y_m"],dw=rb["width_m"]-ra["width_m"],dd=rb["depth_m"]-ra["depth_m"],overlap_m2=inter,iou=inter/uni,label=lab))
wcsv("core_continuity.csv",cont)
maxoff=max(max(abs(c["dx"]),abs(c["dy"]),abs(c["dw"]),abs(c["dd"])) for c in cont)
add("B2.stack_adjacent","continuity","measured","max |dx,dy,dw,dd| for 5 core rooms across L00-L01, L01-L02, L02-L03, L25-L26 (and L03-L25)",maxoff,"m","all footprints identical on all six laid-out levels; IoU=1.0 each pair")
add("B2.stack_L03_L25","continuity","not_testable","continuity through floors L04-L24 (z=24..120)","NOT EVIDENCED","","no rooms/doors/cameras exist for 39 of 45 floors; identical L03 and L25 footprints show a straight stack is CONSISTENT with, not evidence of, continuity. Brief says 'interpolate through intervening floors' = a proposal only")
ov=[]
for lv in LEVELS:
    for c in [r for r in core if r["level_id"]==lv]:
        for o in rooms:
            if o["level_id"]!=lv or o is c: continue
            a=rect(c).intersection(rect(o)).area
            if a>1e-6: ov.append((c["room_id"],o["room_id"],o["name"],a))
add("B3.core_overlap","conflict","measured","area overlaps between core rooms 090-094 and any other room on same level (all 6 levels)","none" if not ov else ov,"m2","edge contact only is not overlap")
def dseg(d):
    h=d["clear_width_m"]/2
    return LineString([(d["x_m"]-h,d["y_m"]),(d["x_m"]+h,d["y_m"])]) if d["axis"]=="x" else LineString([(d["x_m"],d["y_m"]-h),(d["x_m"],d["y_m"]+h)])
drows=[]
for d in doors:
    if d["level_id"] not in LEVELS: continue
    fa,ta=R.get(d["from_room"]),R.get(d["to_room"]);s=dseg(d)
    base=dict(door_id=d["door_id"],level=d["level_id"],type=d["type"],width=d["clear_width_m"],height=d["clear_height_m"],from_room=d["from_room"],to_room=d["to_room"],axis=d["axis"],x=d["x_m"],y=d["y_m"],label="measured")
    if fa is None or ta is None:
        base.update(on_shared_edge="n/a (room id missing)",touches_core="",door_crosses_core_interior="");drows.append(base);continue
    shared=rect(fa).boundary.intersection(rect(ta).boundary)
    base["on_shared_edge"]=bool(shared.buffer(1e-6).contains(s)) if not shared.is_empty else False
    base["touches_core"]=";".join(c["room_id"] for c in core if c["level_id"]==d["level_id"] and s.distance(rect(c))<1e-6)
    base["door_crosses_core_interior"]=";".join(c["room_id"] for c in core if c["level_id"]==d["level_id"] and rect(c).buffer(-1e-6).intersects(s))
    drows.append(base)
wcsv("door_checks_all_levels.csv",drows)
bad=[r for r in drows if r["touches_core"] and r["to_room"][-3:] not in CORE_IDS and r["from_room"][-3:] not in CORE_IDS]
bad2=[r for r in drows if r.get("door_crosses_core_interior")]
bad3=[r for r in drows if r.get("on_shared_edge") is False]
add("B3.door_not_on_shared_edge","conflict","measured","door records on L00-L03,L25,L26 whose segment is not on the shared edge of from_room/to_room rectangles",[r["door_id"] for r in bad3] or "none","")
add("B3.door_through_core_interior","conflict","measured","door segments crossing the interior of a core footprint",[r["door_id"] for r in bad2] or "none","")
add("B3.door_unconnected_touching_core","conflict","measured","doors touching a core footprint where neither from_room nor to_room is a core room",[r["door_id"] for r in bad] or "none","")
sw=[]
for d in doors:
    if d["level_id"] not in LEVELS or d["type"]!="hinged": continue
    disc=Point(d["x_m"],d["y_m"]).buffer(d["clear_width_m"])
    hit=[o["room_id"] for o in rooms if o["level_id"]==d["level_id"] and o["room_id"] not in (d["from_room"],d["to_room"]) and o["room_id"][-3:] in CORE_IDS and disc.intersection(rect(o)).area>1e-6]
    sw.append((d["door_id"],hit))
swcore=[(a,b) for a,b in sw if b]
add("B3.swing_into_unconnected_core","conflict","interpreted (ASSUMED swing = full disc of radius clear width)","hinged doors whose assumed swing disc intrudes into a core room that is neither from_room nor to_room",swcore or "none","","swing radius/hinge side/direction not in data")
for d in [x for x in doors if x["level_id"]=="L00" and x["type"]=="hinged" and x["to_room"][-3:] in("090","091")]:
    st=R[d["to_room"]];h=d["clear_width_m"]/2
    add("B3.stairdoor.%s"%d["door_id"],"stair door","measured","%s (same on all six levels) %.1f x %.1f m at (%.1f,%.1f) axis %s into %s (x %.0f..%.0f, y %.0f..%.0f)"%(d["door_id"],d["clear_width_m"],d["clear_height_m"],d["x_m"],d["y_m"],d["axis"],st["room_id"],st["x_m"],st["x_m"]+st["width_m"],st["y_m"],st["y_m"]+st["depth_m"]),
        "door y-span %.2f..%.2f; distance to stair -y end %.2f, +y end %.2f; offset from stair centre-line %.2f"%(d["y_m"]-h,d["y_m"]+h,d["y_m"]-st["y_m"],st["y_m"]+st["depth_m"]-d["y_m"],d["y_m"]-(st["y_m"]+st["depth_m"]/2)),"m","door is on the stair's outer long side at mid-length, not at an end")
import subprocess
slab=json.loads(subprocess.check_output(["git","-C","C:/q2/r","show","4ce28d8:production/assets/buildings/PI-BLD-0001-V01/EXT/R06/05_ScaleAndPlan/PI-BLD-0001-V01_CrownLandmark_EXT_R06_DesignTargets.json"]))
allz=slab["podium_floor_slab_z_m"]+slab["tower_floor_slab_z_m"]
add("B3.levels","rise","measured","slab z list (EXT R06 DesignTargets: 9 podium + 36 tower slabs)","%d slabs; index of z=18 is %d, z=126 is %d, z=130.5 is %d"%(len(allz),allz.index(18),allz.index(126.0),allz.index(130.5)),"","level index = slab index is interpreted; matches layout z_m for all six levels")
wcsv("rise_per_level.csv",[dict(lower="L%02d"%i,upper="L%02d"%(i+1),z_lower=allz[i],z_upper=allz[i+1],rise_m=allz[i+1]-allz[i],laid_out_lower=("L%02d"%i) in LEVELS,laid_out_upper=("L%02d"%(i+1)) in LEVELS) for i in range(len(allz)-1)])
add("B3.gap","rise","not_testable","L03 (z=18) -> L25 (z=126)","108 m = 6 rises of 6.0 m (L03..L09, to z=54) + 16 rises of 4.5 m (L09..L25); 21 unlaid-out levels L04..L24","m","NO layout for these floors: continuity of lifts/stairs/service through floors 4-24 is NOT evidenced")
add("B3.total_rise","rise","measured","L00->L03 / L03->L25 / L25->L26 / L00->L26","18.0 / 108.0 / 4.5 / 130.5","m")
for lv in LEVELS:
    r=rr(lv,"092");nxt=allz[allz.index(Z[lv])+1]
    add("B3.f2f.%s"%lv,"clear height","measured","%s floor-to-floor to next slab %.1f m vs core clear_height_m %.1f"%(lv,nxt-Z[lv],r["clear_height_m"]),round(nxt-Z[lv]-r["clear_height_m"],3),"m","difference = slab+ceiling build-up (interpreted). Core clear height is LESS than one rise, so stairs/shafts need the upper slab open (planning OBJ omits stair/shaft plates)")
for rs,tot in((6.0,36),(4.5,28)):
    add("B3.proposed_riser.%s"%rs,"stair","measured (arithmetic on proposed brief/MD06)","rise %.1f m / %d risers (1.8 m clear, 0.30 m tread, two flights)"%(rs,tot),round(rs/tot,4),"m per riser","%d risers/flight if two equal flights (interpreted); treads/landing depth not given"%(tot//2))
add("B3.stair_totals","stair","measured (arithmetic on proposed)","risers needed along proposed 36 / 28 counts","L00->L03: 3x36=108; L03->L25: 6x36+16x28=664; L25->L26: 28","risers","only the six laid-out rises are in the layout; the 21 unlaid-out floors are arithmetic on target slab z")
add("B3.stair_run_proposed","stair","interpreted (ASSUMED treads per flight = risers-1)","going per flight at proposed 0.30 m tread","18 risers->17 treads=5.10 m; 14 risers->13 treads=3.90 m","m","tread count/landing depth not in data")
sweep=[]
for rise_m,clear in((6.0,5.4),(4.5,3.6)):
  for rv in (0.15,0.16,0.17,0.175,0.18,0.19):
    n=math.ceil(rise_m/rv-1e-9); n+= n%2
    act=rise_m/n; per=n//2; treads=per-1; run=treads*0.30
    for land in (1.2,1.5,1.8):
        length=run+2*land
        sweep.append(dict(rise_m=rise_m,ASSUMED_max_riser_m=rv,risers_total=n,actual_riser_m=round(act,4),risers_per_flight=per,ASSUMED_treads_per_flight=treads,going_per_flight_m_at_0p30=round(run,3),ASSUMED_landing_depth_m=land,plan_length_two_flight_m=round(length,3),fits_in_14m_y_axis=length<=14.0,fits_in_8m_x_axis=length<=8.0,label="ASSUMPTION SWEEP - not a design fact; only 0.30 tread and 1.8 clear are PROPOSED"))
wcsv("stair_assumption_sweep.csv",sweep)
hs=[]
for rise_m,clear,tot in((6.0,5.4,36),(4.5,3.6,28)):
    r=rise_m/tot;per=tot//2
    for H in (1.9,2.0,2.1,2.2):
        mid=rise_m/2;mid_head=clear-mid
        k_bad=[k for k in range(1,per+1) if clear-(mid+k*r)<H]
        hs.append(dict(rise_m=rise_m,clear_height_m=clear,riser_proposed_m=round(r,4),ASSUMED_headroom_m=H,mid_landing_height_m=mid,mid_landing_headroom_to_upper_soffit_m=round(mid_head,3),mid_landing_ok=mid_head>=H,flight2_risers_below_ASSUMED_headroom=len(k_bad),min_upper_slab_opening_run_m_at_0p30=round(len(k_bad)*0.30,2),label="ASSUMPTION SWEEP; soffit = clear_height_m above lower floor (interpreted); no stair geometry exists"))
wcsv("stair_headroom_sweep.csv",hs)
h25=[x for x in hs if x["rise_m"]==4.5 and x["ASSUMED_headroom_m"]==2.0][0]
h6=[x for x in hs if x["rise_m"]==6.0 and x["ASSUMED_headroom_m"]==2.0][0]
add("B3.headroom_sweep","stair","interpreted (ASSUMED 2.0 m headroom; sweep 1.9-2.2)","mid-landing headroom to upper soffit","6.0 m rise: %.2f m (ok at 2.0); 4.5 m rise: %.2f m (BELOW 2.0 for every H in 1.9-2.2 unless upper slab is open above mid-landing)"%(h6["mid_landing_headroom_to_upper_soffit_m"],h25["mid_landing_headroom_to_upper_soffit_m"]),"m","L25/L26 clear 3.6 vs 4.5 rise; planning OBJ leaves stair zones open (no floor plate), which would remove the issue - not modelled")
dpos=[]
for sid in ("090","091"):
    st=rr("L00",sid);d=[x for x in doors if x["level_id"]=="L00" and x["to_room"].endswith(sid) and x["type"]=="hinged"][0]
    ds=(d["y_m"]-d["clear_width_m"]/2,d["y_m"]+d["clear_width_m"]/2)
    for n_r,run in((18,5.1),(14,3.9)):
        for land in (1.2,1.5,1.8):
            for anchor in("-y end","+y end"):
                if anchor=="-y end": a0=st["y_m"]+land;a1=a0+run
                else: a1=st["y_m"]+st["depth_m"]-land;a0=a1-run
                over=min(a1,ds[1])-max(a0,ds[0])
                dpos.append(dict(stair=st["room_id"],door=d["door_id"],door_y0=ds[0],door_y1=ds[1],risers_per_flight=n_r,ASSUMED_landing_depth=land,ASSUMED_anchor=anchor,flight_y0=round(a0,2),flight_y1=round(a1,2),door_span_overlaps_flight_m=round(max(over,0),2),label="ASSUMED layout (flight along Y from one landing end); not a design fact"))
wcsv("stair_door_vs_assumed_flight.csv",dpos)
ovl=[x for x in dpos if x["door_span_overlaps_flight_m"]>0]
add("B3.stairdoor_flight","stair door","interpreted (ASSUMED flight placement)","D084/D085 door span (y -0.75..0.75) vs an assumed flight run in stair y -8..6","%d of %d sweep combos overlap a flight; overlaps occur for flight anchored at +y end (18-riser flight spans y -0.9..4.2 at 1.8 m landing)"%(len(ovl),len(dpos)),"","real stair placement unknown - a risk, not a measured clash")
add("B3.stair_orientation","stair","interpreted (ASSUMED)","8.0 m X vs 14.0 m Y stair room","two-flight 18-riser run needs 8.1-8.7 m plan length at assumed 1.2-1.8 m landings > 8.0 m; fits 14 m. Width: 2x1.8 = 3.6 m of 8.0 m","m","")
add("B3.missing","missing","not_testable","lift pit/overrun/machine room/speed, cab door swing, stair landing depth/handrail/headroom geometry, service-lift cab size, fire lobby/refuge","NOT IN DATA","","only: cabin target 2.8x3.2x2.7 m (MD04), cell 4x4.8, lift door 1.5x2.4, service door 1.8x2.6, service shaft 4x5.2 (MD05), stair 1.8 clear/0.30 tread/36 or 28 risers (MD06)")
add("B3.cab_in_cell","lift","measured (arithmetic on proposed)","cab 2.8x3.2 in 4x4.8 cell","side clearance 0.6 each, depth spare 1.6","m")
add("B3.lift_door_vs_cab","lift","measured","lift door clear 1.5x2.4 vs cab 2.8x2.7","door/cab width = 0.536; door 0.30 m lower than cab height","m","")
add("B3.lift_landing","lift","measured","lift hall RM080 y -16..-8 in front of door line y=-8","8.0 m landing depth vs cab depth 3.2","m")
dd=[(x["door_id"],x["x_m"]) for x in doors if x["level_id"]=="L00" and x["to_room"].endswith("092")]
add("B3.lift_doors_x","lift","measured","passenger lift door centres L00 "+str(dd)+" vs cell centres -4,0,4","door edge to cell wall 1.25 m; clear between adjacent door edges 2.5 m","m")
add("B3.service_door","lift","measured","D090 (8,2) 1.8 wide vs service shaft x 6..10 (notes/MD05)","edge margin 1.1 m each side; room RM093 is x -10..10 (20 x 5.2): 16 m beyond the 4 m shaft is MEP reserve (interpreted)","m")
add("B3.service_separation","service","interpreted","RM093 (y -3.2..2) shares the y=-3.2 edge with passenger shaft room RM092 over x -6..6 (12 m)","back-to-back, no door between; service lift has no door to the lift hall; route RM094 -> D091 (8,6) -> cross corridor RM083","")
caps=[]
for dm in (0.6,0.7,0.8,0.9,1.0):
    for nm,w in(("passenger lift door",1.5),("service lift door",1.8),("hinged door 1.5",1.5),("service door 1.2 (MD01)",1.2),("stair flight clear",1.8),("cab interior width",2.8)):
        caps.append(dict(ASSUMED_capsule_diameter_m=dm,opening=nm,opening_width_m=w,side_clearance_m=round((w-dm)/2,3),passes_by_width=w>dm,label="sweep 0.6-1.0 m; real capsule UNKNOWN; width only"))
wcsv("capsule_sweep.csv",caps)
add("B5.capsule","capsule","interpreted (ASSUMED 0.6-1.0 m diameter)","lift door records: 1.5 m (18 passenger records) and 1.8 m (6 service records)","side clearance 0.25..0.45 m (1.5 m) / 0.40..0.60 m (1.8 m); all pass by width","m","width only; sill/threshold, door timing, capsule height and step-up ability unknown (riser 0.1607-0.1667 m is proposed-derived)")
def margin_to(reg,rc):
    if reg is None: return None
    if reg.contains(rc): return rc.exterior.distance(reg.exterior if reg.geom_type=="Polygon" else reg.boundary)
    return -max((0 if reg.contains(Point(c)) else reg.exterior.distance(Point(c))) for c in rc.exterior.coords)
zcache={}
def skin_region(nm,z):
    k=(nm,round(z,3))
    if k not in zcache: zcache[k]=zone([nm],z)
    zn=zcache[k]
    if zn is None: return None
    outer,hole=zn
    return hole if (hole is not None and not hole.is_empty) else outer
PW={"L00":"Podium_wall_1","L01":"Podium_wall_1","L02":"Podium_wall_1","L03":"Podium_wall_2"}
pub={r["room_id"]:r for r in csv.DictReader(open("C:/q2/r/production/handoffs/quik/2026-10-16/crown-landmark/FIT-COVERAGE/C02/C02_FIT_COVERAGE.csv"))}
ribs=["Rib_R%d"%i for i in range(1,7)]
def rib_dist(rc,z0,z1,n=9):
    best=(1e9,None,None)
    for z in np.linspace(z0,z1,n):
        for rn in ribs:
            segs=slice_segs([rn],float(z))
            if not segs: continue
            u=unary_union(segs);polys=list(polygonize(u))
            geom=unary_union(polys) if polys else u
            dd=geom.distance(rc)
            if dd<best[0]: best=(dd,rn,float(z))
    return best
fit=[]
for r in sorted(core+[R["%s-RM080"%lv] for lv in LEVELS],key=lambda r:(LEVELS.index(r["level_id"]),r["room_id"])):
    lv=r["level_id"];rc=rect(r);z0=r["z_m"];z1=z0+r["clear_height_m"]
    if lv in PW: nm=PW[lv];zs=[z0+0.5]
    else: nm="Tower_curtainwall_skin";zs=[z0+0.01,z1-0.01]
    m=min(margin_to(skin_region(nm,z),rc) for z in zs)
    rd=rib_dist(rc,z0,z1)
    pm=float(pub[r["room_id"]]["wall_margin_m"]) if r["room_id"] in pub and pub[r["room_id"]]["wall_margin_m"] else None
    fit.append(dict(room_id=r["room_id"],level=lv,name=r["name"],enclosure=nm,slice_z=";".join("%.2f"%z for z in zs),wall_margin_m=round(m,3),published_C02_wall_margin_m=None if pm is None else round(pm,3),diff_vs_published=None if pm is None else round(m-pm,3),nearest_rib=rd[1],rib_clearance_m=round(rd[0],3),rib_at_z=rd[2],rib_intersects=rd[0]<=1e-9,label="measured (C02 mesh slice; rib clearance = min over 9 z samples in room z-range)"))
wcsv("core_shell_rib_fit.csv",fit)
coreonly=[x for x in fit if x["room_id"][-3:] in CORE_IDS]
mn=min(coreonly,key=lambda x:x["wall_margin_m"]);mr=min(coreonly,key=lambda x:x["rib_clearance_m"])
for lv in LEVELS:
    c=[x for x in coreonly if x["level"]==lv]
    a=min(c,key=lambda x:x["wall_margin_m"]);b=min(c,key=lambda x:x["rib_clearance_m"])
    add("B4.fit.%s"%lv,"shell fit","measured","%s core rooms 090-094 min wall margin / min rib clearance"%lv,"wall %.2f m (%s, %s); rib %.2f m (%s at z=%.1f, %s)"%(a["wall_margin_m"],a["enclosure"],a["room_id"],b["rib_clearance_m"],b["nearest_rib"],b["rib_at_z"],b["room_id"]),"m","positive = inside / clear")
dif=[abs(x["diff_vs_published"]) for x in coreonly if x["diff_vs_published"] is not None]
add("B4.fit.worst","shell fit","measured","overall minimum wall margin / rib clearance, core rooms 090-094","wall %s m (%s); rib %s m (%s vs %s)"%(mn["wall_margin_m"],mn["room_id"],mr["rib_clearance_m"],mr["room_id"],mr["nearest_rib"]),"m","max |diff| vs published C02_FIT_COVERAGE wall_margin: %.3f m (n=%d)"%(max(dif),len(dif)))
ext=[];corerects={s:rr("L00",s) for s in CORE_IDS}
for i,z in enumerate(allz):
    if not (18<=z<=126): continue
    if z<54: nm="Podium_wall_2" if z<36 else "Podium_wall_3";zz=z+0.5
    else: nm="Tower_curtainwall_skin";zz=z+0.01
    reg=skin_region(nm,zz)
    for s,r in corerects.items():
        ext.append(dict(level="L%02d"%i,z_m=z,slice_z=zz,enclosure=nm,room_footprint=s,margin_m=round(margin_to(reg,rect(r)),3),laid_out=("L%02d"%i) in LEVELS,label="interpreted (core footprint extruded; not a layout fact)"))
wcsv("extrapolated_stack_vs_shell.csv",ext)
em=min(ext,key=lambda x:x["margin_m"])
add("B4.extrapolated","shell fit","interpreted","L03 core footprints straight-extruded to each slab z=18..126 vs C02 wall/skin","min margin %s m at %s z=%s (%s, rooms %s); all margins >=0: %s"%(em["margin_m"],em["level"],em["z_m"],em["enclosure"],em["room_footprint"],all(x["margin_m"]>=0 for x in ext)),"m","shows the C02 skin does not obstruct a straight stack; says nothing about structure/MEP/slabs (not modelled in C02)")
names=[n for n in mesh if re.search("core|lift|stair|shaft|slab|floor",n,re.I)]
add("B4.c02_core_geometry","shell","measured","C02 GLB meshes whose name matches core/lift/stair/shaft/slab/floor",names or "none","","C02 models no core, shaft, stair or slab; fit is plan-vs-skin only")
json.dump(F,open(OUT+"findings.json","w"),indent=1,default=str)
with open(OUT+"findings.csv","w",newline="") as f:
    w=csv.DictWriter(f,fieldnames=["id","topic","label","item","value","unit","note"]);w.writeheader()
    for x in F: w.writerow({k:(json.dumps(v,default=str) if isinstance(v,(list,dict)) else v) for k,v in x.items()})
for x in F: print(x["id"],"|",x["label"][:12],"|",x["item"][:80],"=>",str(x["value"])[:220])
