import sys,json,csv,math,collections
sys.path.insert(0,'C:/q2/out/C_ribs')
import numpy as np
from glb_load import load,slice_segments
from shapely.geometry import LineString,box,Point,MultiPolygon,Polygon,MultiLineString
from shapely.ops import unary_union,polygonize
import shapely
OUT='C:/q2/out/C_ribs/'
mesh=load()
LAY=json.load(open('C:/q2/layout.json'))
rooms=LAY['rooms'];doors=LAY['doors']
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'))}
LVZ={}
for r in rooms: LVZ[r['level_id']]=r['z_m']
ROOM={r['room_id']:r for r in rooms}
def family(n):
    if n.startswith(('Rib_R','Gold_inner_R','Crown_glass_R')): return 'RIB'
    if n.startswith(('Mullion_','Storey_band_')): return 'MULL'
    if n.startswith(('Front_amber','Rear_crossed','Front_atrium','Central_glazed')): return 'ATRIUM'
    if n.startswith(('Tower_curtain','Podium_wall','T1_','T2_','T3_','Cantilever','Main_entry','Entry_glass','Canopy','Terrace','Basin')): return 'ENCL'
    return None   # Foundation, Deck_*, Occupied_roof: slabs, not intrusions
def is_closed(v,t):
    key={};vi=np.array([key.setdefault(tuple(np.round(p,4)),len(key)) for p in v]);tt=vi[t]
    e=collections.Counter()
    for tr in tt:
        for a,b in((0,1),(1,2),(2,0)): e[tuple(sorted((tr[a],tr[b])))]+=1
    return all(c==2 for c in e.values())
PARTS={}
for n,(v,t) in mesh.items():
    f=family(n)
    if f is None: continue
    PARTS[n]=dict(fam=f,closed=is_closed(v,t),bmin=v.min(0),bmax=v.max(0),ntri=len(t))
def bbox_hits(n,x0,y0,x1,y1,z0,z1,pad=0.0):
    p=PARTS[n];a,b=p['bmin'],p['bmax']
    return not(b[0]<x0-pad or a[0]>x1+pad or b[1]<y0-pad or a[1]>y1+pad or b[2]<z0 or a[2]>z1)
_cache={}
def geom(n,z):
    """-> (solid polygon geometry or None [closed parts, filled], trace lines geometry or None [open parts])"""
    k=(n,round(z,3))
    if k in _cache: return _cache[k]
    v,t=mesh[n];s=slice_segments(v,t,z)
    res=(None,None)
    if len(s):
        ls=[LineString(np.round(x,4)) for x in s if np.hypot(*(x[0]-x[1]))>1e-9]
        if ls:
            u=unary_union(ls)
            if PARTS[n]['closed']:
                faces=[Polygon(p.exterior) for p in polygonize(u)]
                # even-odd via symmetric difference of filled ring faces
                g=None
                for f in faces:
                    g=f if g is None else g.symmetric_difference(f)
                res=(g if g is not None and not g.is_empty else None,None)
            else:
                res=(None,u)
    _cache[k]=res
    return res
def heights(z0,z1,step=0.25):
    lo,hi=z0+0.1,z1-0.1
    return list(np.round(np.arange(lo,hi+1e-9,step),3))
def depth_into(g,rect):
    """max distance (m) from the room boundary reached by geometry g inside rect (vertices densified to 0.05 m)"""
    if g is None or g.is_empty: return 0.0
    gi=g.intersection(rect)
    if gi.is_empty: return 0.0
    gd=shapely.segmentize(gi,0.05)
    pts=shapely.get_coordinates(gd)
    pts=np.vstack([pts,np.array([[gi.centroid.x,gi.centroid.y]])])
    return float(max(rect.exterior.distance(Point(p)) for p in pts[::max(1,len(pts)//4000)] ) ) if len(pts) else 0.0
def doors_of(rid): return [d for d in doors if d['from_room']==rid or d['to_room']==rid]
def dseg(d):
    w=d['clear_width_m']
    return LineString([(d['x_m']-w/2,d['y_m']),(d['x_m']+w/2,d['y_m'])]) if d['axis']=='x' else LineString([(d['x_m'],d['y_m']-w/2),(d['x_m'],d['y_m']+w/2)])

# ---------------- TASK 1 ----------------
t1=[];room_summary={}
detail_geom={}  # (room,part) -> union footprint in rect
for r in rooms:
    rid=r['room_id'];z0=r['z_m'];z1=z0+r['clear_height_m']
    x0,y0=r['x_m'],r['y_m'];x1,y1=x0+r['width_m'],y0+r['depth_m'];rect=box(x0,y0,x1,y1)
    H3=[z0+0.1,(z0+z1)/2,z1-0.1];Hf=sorted(set(heights(z0,z1))|set(np.round(H3,3)))
    rd=doors_of(rid)
    for n,p in PARTS.items():
        if not bbox_hits(n,x0,y0,x1,y1,z0,z1): continue
        per={};areas=[];trace=[];zs=[];ug=[]
        for z in Hf:
            s,l=geom(n,z)
            a=0.0;tl=0.0;gi=None
            if s is not None:
                gi=s.intersection(rect);a=gi.area
                if a<1e-6: gi=None;a=0.0
            if l is not None:
                li=l.intersection(rect);tl=li.length
                if tl<1e-4: tl=0.0
                else: gi=li if gi is None else unary_union([gi,li])
            per[z]=(a,tl)
            if a>0 or tl>0: areas.append(a);trace.append(tl);zs.append(z);ug.append(gi)
        if not zs: continue
        U=unary_union(ug)
        seen3=[ (per[round(h,3)][0]>0 or per[round(h,3)][1]>0) for h in H3 ]
        dist_doors=[(d['door_id'],dseg(d).distance(U)) for d in rd]
        near=[x for x in dist_doors if x[1]<=1.0]
        # depth at max-area height
        zmax=zs[int(np.argmax(areas))] if max(areas)>0 else zs[int(np.argmax(trace))]
        s,l=geom(n,zmax);gmax=s if s is not None else l
        rec=dict(room_id=rid,level_id=r['level_id'],part=n,family=p['fam'],closed_mesh=p['closed'],
            max_slice_area_m2=round(max(areas),3),max_trace_len_m=round(max(trace),3),
            area_bottom_m2=round(per[round(H3[0],3)][0],3),area_mid_m2=round(per[round(H3[1],3)][0],3),area_top_m2=round(per[round(H3[2],3)][0],3),
            seen_at_3_heights=seen3,z_first_m=min(zs),z_last_m=max(zs),z_at_max_m=zmax,
            plan_footprint_union_m2=round(U.area,3) if U.area>0 else 0.0,
            footprint_bounds_xyxy=[round(c,3) for c in U.bounds],
            max_depth_from_room_edge_m=round(depth_into(gmax,rect),3),
            doors_checked=[d['door_id'] for d in rd],
            nearest_door=min(dist_doors,key=lambda x:x[1])[0] if dist_doors else None,
            nearest_door_dist_m=round(min(x[1] for x in dist_doors),3) if dist_doors else None,
            door_within_1m=[x[0] for x in near])
        t1.append(rec);detail_geom[(rid,n)]=U
print('task1 room/part intrusions:',len(t1))
by=collections.defaultdict(list)
for x in t1: by[x['room_id']].append(x)
for k,v in by.items():
    print(k,collections.Counter(x['family'] for x in v), [ (x['part'],x['max_slice_area_m2'],x['max_depth_from_room_edge_m']) for x in v if x['family']!='ENCL'][:6])
json.dump(t1,open(OUT+'task1_room_intrusions.json','w'),indent=1,default=str)
