import json,struct,csv,collections,sys,numpy as np
# usage: python refit_c02.py <C02.glb> <INTERIOR_LAYOUT.json> <C02_FIT_COVERAGE.csv> <out.csv>
GLB_PATH,LAYOUT_PATH,PUB_PATH,OUT_PATH=sys.argv[1:5]
from shapely.geometry import box,LineString,Polygon
from shapely.ops import unary_union,polygonize
GLB=GLB_PATH
b=open(GLB,"rb").read();ln=struct.unpack("<I",b[8:12])[0];off=12;js=bn=None
while off<ln:
    cl,ct=struct.unpack("<II",b[off:off+8]);cd=b[off+8:off+8+cl];off+=8+cl
    if ct==0x4E4F534A: js=json.loads(cd)
    else: bn=cd
def acc(i):
    a=js["accessors"][i];bv=js["bufferViews"][a["bufferView"]];o=bv.get("byteOffset",0)+a.get("byteOffset",0)
    nc={"SCALAR":1,"VEC3":3}[a["type"]];dt={5126:np.float32,5125:np.uint32,5123:np.uint16}[a["componentType"]]
    return np.frombuffer(bn,dtype=dt,count=a["count"]*nc,offset=o).reshape(-1,nc)
mesh={}
for n in js["nodes"]:
    assert not any(k in n for k in("matrix","rotation","translation","scale","children"))
    p=js["meshes"][n["mesh"]]["primitives"][0]
    v=acc(p["attributes"]["POSITION"]).astype(float)
    src=np.c_[v[:,0],-v[:,2],v[:,1]]   # source frame: x right, y back (front=-y), z up
    t=acc(p["indices"]).reshape(-1,3).astype(int)
    mesh[n["name"]]=(src,t)
def slice_segs(names,z):
    segs=[]
    for nm in names:
        v,t=mesh[nm];tri=v[t]              # (n,3,3)
        zz=tri[:,:,2]-z
        for k in range(len(tri)):
            s=zz[k]
            if s.min()>0 or s.max()<0: continue
            pts=[]
            for a,c in((0,1),(1,2),(2,0)):
                if (s[a]>0)!=(s[c]>0):
                    u=s[a]/(s[a]-s[c]);pts.append(tri[k,a,:2]+u*(tri[k,c,:2]-tri[k,a,:2]))
            if len(pts)==2 and np.hypot(*(pts[0]-pts[1]))>1e-9: segs.append(__import__("shapely").set_precision(LineString([tuple(pts[0]),tuple(pts[1])]),1e-4))
    return segs
def interior(names,z):
    segs=slice_segs(names,z)
    u=unary_union(segs); polys=list(polygonize(u))
    if not polys: return None
    outer=max(polys,key=lambda p:p.area)           # largest ring = outer wall face
    # wall ring = polygons with holes; room zone = union of all holes of the outer polygon, else the polygon's void
    merged=unary_union(polys)
    return merged
def zone(names,z):
    m=interior(names,z)
    if m is None: return None
    polys=[m] if m.geom_type=="Polygon" else list(m.geoms)
    outer=max(polys,key=lambda p:p.area)
    holes=[Polygon(r) for r in outer.interiors]
    return Polygon(outer.exterior), (unary_union(holes) if holes else None)
L=json.load(open(LAYOUT_PATH))["rooms"]
pub={r["room_id"]:r for r in csv.DictReader(open(PUB_PATH,encoding="utf-8"))}
PW={"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"}
out=[];cache={}
for r in L:
    rid=r["room_id"];lv=r["level_id"]
    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"]
    if lv in PW:
        nm=PW[lv];zs=[min(z0+0.5,mesh[nm][0][:,2].max()-0.5)]
    else:
        nm="Tower_curtainwall_skin";zs=[z0+0.01,z1-0.01]
    margins=[]
    for z in zs:
        key=(nm,round(z,2))
        if key not in cache: cache[key]=zone([nm],z)
        zn=cache[key]
        if zn is None: margins.append(None);continue
        outer,hole=zn
        # inner void bounds the room; if no hole (single surface skin) use outer polygon
        reg=hole if (hole is not None and not hole.is_empty) else outer
        if reg.contains(rect): margins.append(rect.exterior.distance(reg.exterior) if reg.geom_type=="Polygon" else rect.exterior.distance(reg.boundary))
        else:
            margins.append(-reg.boundary.distance(rect.exterior) if reg.intersects(rect) else -float(reg.distance(rect))-0.0)
            # signed: negative = how far the worst rect vertex lies outside
            worst=max(reg.exterior.distance(__import__("shapely").geometry.Point(c)) if not reg.contains(__import__("shapely").geometry.Point(c)) else 0 for c in rect.exterior.coords)
            margins[-1]=-worst
    m=min(x for x in margins if x is not None) if any(x is not None for x in margins) else None
    # deck outline margin (bbox of deck part)
    deckm=None
    if lv in DECK:
        dv=mesh[DECK[lv]][0];dx0,dy0,dx1,dy1=dv[:,0].min(),dv[:,1].min(),dv[:,0].max(),dv[:,1].max()
        deckm=min(r["x_m"]-dx0,dx1-(r["x_m"]+r["width_m"]),r["y_m"]-dy0,dy1-(r["y_m"]+r["depth_m"]))
    st=None if m is None else ("FITS" if m>=1.2-1e-3 else ("INSIDE_BELOW_ALLOWANCE" if m>=0 else ("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"))))
    out.append((rid,lv,m,deckm,st,pub[rid]["status"],float(pub[rid]["wall_margin_m"]) if pub[rid]["wall_margin_m"] else None))
c=collections.Counter(o[4] for o in out);print("MY statuses:",dict(c))
dis=[o for o in out if o[4]!=o[5]];print("status disagreements with published CSV:",len(dis))
for o in dis: print(" ",o)
d=[abs(o[2]-o[6]) for o in out if o[2] is not None and o[6] is not None]
print("margin diff vs published: max %.3f m, mean %.3f m, n=%d, >0.05 m: %d"%(max(d),sum(d)/len(d),len(d),sum(x>0.05 for x in d)))
for o in out:
    if o[1] in("L00","L01","L02","L03") and o[4]!="FITS": print(o[0],"my margin %.2f deck %.2f"%(o[2],o[3]),o[4],"| pub",o[5],o[6])
big=sorted(((abs(o[2]-o[6]),o) for o in out if o[2] is not None and o[6] is not None),reverse=True)[:6]
print("largest margin diffs:");[print(" %.2f"%a,o[0],"mine %.2f pub %.2f"%(o[2],o[6])) for a,o in big]

with open(OUT_PATH,"w",newline="",encoding="utf-8") as f:
    w=csv.writer(f);w.writerow(["room_id","level_id","my_wall_margin_m","deck_margin_m","my_status","published_status","published_wall_margin_m"])
    for o in out: w.writerow([o[0],o[1],"" if o[2] is None else round(float(o[2]),4),"" if o[3] is None else round(float(o[3]),4),o[4],o[5],o[6]])
