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)

# ---------------- helpers for obstacle unions ----------------
def obstacle_union(rect_pad,z0,z1,fams,names=None,step=0.25):
    """union of filled solids + traces of parts of given families within bbox rect_pad over z0..z1; returns (geom, per-part dict)"""
    x0,y0,x1,y1=rect_pad.bounds
    parts={}
    for n,p in PARTS.items():
        if p['fam'] not in fams: continue
        if names and n not in names: continue
        if not bbox_hits(n,x0,y0,x1,y1,z0,z1): continue
        gs=[]
        for z in heights(z0,z1,step):
            s,l=geom(n,z)
            for g in (s,l):
                if g is not None and g.intersects(rect_pad): gs.append(g)
        if gs: parts[n]=unary_union(gs)
    return (unary_union(list(parts.values())) if parts else None),parts

# ---------------- near-miss distance per room ----------------
near=[]
for r in rooms:
    rid=r['room_id'];z0=r['z_m'];z1=z0+r['clear_height_m']
    rect=box(r['x_m'],r['y_m'],r['x_m']+r['width_m'],r['y_m']+r['depth_m'])
    pad=rect.buffer(8.0)
    for fam in ('RIB','MULL','ATRIUM'):
        U,parts=obstacle_union(pad,z0,z1,{fam})
        if not parts:
            near.append(dict(room_id=rid,family=fam,nearest_part=None,nearest_dist_m=None,note='no part of this family within 8 m (plan) of the room rect over its z range'));continue
        d={n:g.distance(rect) for n,g in parts.items()}
        n=min(d,key=d.get)
        near.append(dict(room_id=rid,family=fam,nearest_part=n,nearest_dist_m=round(d[n],3),note=''))
json.dump(near,open(OUT+'task1b_nearest_by_room.json','w'),indent=1)
nd=[x for x in near if x['nearest_dist_m'] is not None and x['nearest_dist_m']<=1.0]
print('rooms w/ rib/mull/atrium family within 1.0 m:',[(x['room_id'],x['family'],x['nearest_part'],x['nearest_dist_m']) for x in nd])
print('L25/L26 nearest:',[(x['room_id'],x['family'],x['nearest_part'],x['nearest_dist_m']) for x in near if x['room_id'][:3] in('L25','L26')])

# ---------------- TASK 3 doors ----------------
t3=[]
for d in doors:
    z0=LVZ[d['level_id']];z1=z0+d['clear_height_m'];seg=dseg(d);w=d['clear_width_m']
    ax=d['axis']
    if ax=='x': appr=box(d['x_m']-w/2,d['y_m']-1.0,d['x_m']+w/2,d['y_m']+1.0)
    else: appr=box(d['x_m']-1.0,d['y_m']-w/2,d['x_m']+1.0,d['y_m']+w/2)
    rec=dict(door_id=d['door_id'],level_id=d['level_id'],x_m=d['x_m'],y_m=d['y_m'],axis=ax,clear_width_m=w,clear_height_m=d['clear_height_m'],type=d['type'],from_room=d['from_room'],to_room=d['to_room'])
    pad=seg.buffer(6.0)
    for fam in ('RIB','MULL','ATRIUM','ENCL'):
        U,parts=obstacle_union(box(*(seg.buffer(80.0 if fam!='ENCL' else 6.0)).bounds),z0,z1,{fam})
        if not parts:
            rec[fam+'_nearest']=None;rec[fam+'_dist_m']=None;rec[fam+'_open_width_after_m']=w;rec[fam+'_status']='NONE_WITHIN_SEARCH_BOX';continue
        dist={n:g.distance(seg) for n,g in parts.items()};n=min(dist,key=dist.get);dm=dist[n]
        cov=U.intersection(seg).length if U is not None else 0.0
        inter=U.intersection(appr) if U is not None else None
        proj=0.0
        if inter is not None and not inter.is_empty:
            iv=[]
            for gg in getattr(inter,'geoms',[inter]):
                if gg.is_empty: continue
                b=gg.bounds
                iv.append((b[0],b[2]) if ax=='x' else (b[1],b[3]))
            iv.sort();cur=None;tot=0
            for a,b in iv:
                if cur is None: cur=[a,b]
                elif a<=cur[1]: cur[1]=max(cur[1],b)
                else: tot+=cur[1]-cur[0];cur=[a,b]
            if cur: tot+=cur[1]-cur[0]
            proj=tot
        open_w=max(0.0,w-max(cov,proj))
        st='BLOCKS' if open_w<=1e-6 and (cov>0 or proj>0) else ('NARROWS' if (cov>0.001 or proj>0.001) else ('NEAR_<=1.0m' if dm<=1.0 else 'CLEAR'))
        rec[fam+'_nearest']=n;rec[fam+'_dist_m']=round(dm,3);rec[fam+'_seg_covered_m']=round(cov,3);rec[fam+'_approach1m_projected_m']=round(proj,3);rec[fam+'_open_width_after_m']=round(open_w,3);rec[fam+'_status']=st
    t3.append(rec)
print('doors:',len(t3))
for fam in ('RIB','MULL','ATRIUM','ENCL'):
    print(fam,collections.Counter(r[fam+'_status'] for r in t3))
    for r in t3:
        if r[fam+'_status'] in('BLOCKS','NARROWS','NEAR_<=1.0m'): print('  ',r['door_id'],r[fam+'_nearest'],r[fam+'_dist_m'],r[fam+'_open_width_after_m'],r[fam+'_status'])
json.dump(t3,open(OUT+'task3_doors.json','w'),indent=1)

# ---------------- TASK 4a: L03-RM001 vs Rib_R1 ----------------
r=ROOM['L03-RM001'];z0=r['z_m'];z1=z0+r['clear_height_m']
rect=box(r['x_m'],r['y_m'],r['x_m']+r['width_m'],r['y_m']+r['depth_m'])
rows=[]
for z in list(np.round(np.arange(z0,z1,0.25),3))+[z1-0.01]:
    s,l=geom('Rib_R1',z)
    if s is None:
        rows.append(dict(z=float(z),area_in_room_m2=0.0,rib_bounds=None));continue
    gi=s.intersection(rect)
    rows.append(dict(z=float(z),z_above_floor=round(float(z)-z0,3),rib_area_total_m2=round(s.area,3),rib_bounds=[round(c,3) for c in s.bounds],area_in_room_m2=round(gi.area,4),
        in_room_bounds=[round(c,3) for c in gi.bounds] if not gi.is_empty else None,
        max_depth_m=round(depth_into(s,rect),3)))
sh=shapely.affinity.translate(rect,0,4.8)
_s=[]
for z in list(np.arange(z0,z1,0.05))+[z1-0.001]:
    q=geom('Rib_R1',z)[0]
    if q is not None: _s.append(q)
_ru=unary_union(_s)
shift48_overlap_area=round(sh.intersection(_ru).area,4)
solids=[]
for z in list(np.arange(z0,z1,0.05))+[z1-0.001]:
    s=geom('Rib_R1',z)[0]
    if s is not None: solids.append(s)
RU=unary_union(solids)
tr={}
for nm,(dx,dy) in {'+x':(1,0),'-x':(-1,0),'+y(rear)':(0,1),'-y(front)':(0,-1)}.items():
    s_=0.0
    while s_<30:
        if not shapely.affinity.translate(rect,dx*s_,dy*s_).intersects(RU.buffer(-1e-6)): break
        s_+=0.005
    tr[nm]=round(s_,3)
inter=rect.intersection(RU)
rem=rect.difference(RU)
# first z where Rib_R1 enters room (fine bisection)
zin=None
for z in np.arange(z0,z1,0.01):
    s=geom('Rib_R1',z)[0]
    if s is not None and s.intersection(rect).area>1e-6: zin=float(z);break
t4a=dict(room='L03-RM001',overlap_area_if_room_moved_4p8m_rearward_m2=shift48_overlap_area,room_rect_xyxy=list(rect.bounds),z_floor=z0,z_ceiling=z1,
    rib_enters_room_at_z=zin,rib_enters_at_height_above_floor_m=(None if zin is None else round(zin-z0,3)),
    envelope_area_m2=round(inter.area,4),envelope_bounds_xyxy=[round(c,3) for c in inter.bounds],
    max_area_slice_m2=max(x['area_in_room_m2'] for x in rows),
    published_rib_intrusions=PUB['L03-RM001']['rib_intrusions'],min_translation_to_clear_m=tr,
    room_area_m2=rect.area,remaining_area_m2=round(rem.area,3),remaining_components=(len(rem.geoms) if hasattr(rem,'geoms') else 1),
    slices=rows)
json.dump(t4a,open(OUT+'task4a_L03RM001_RibR1.json','w'),indent=1)
print('L03-RM001',json.dumps({k:v for k,v in t4a.items() if k!='slices'}))
print([ (x['z'],x.get('area_in_room_m2'),x.get('max_depth_m')) for x in rows if x.get('area_in_room_m2')])

# ---------------- TASK 4b/5: capsule sweep + room splitting, all rooms ----------------
SWEEP=[0.6,0.7,0.8,1.0]
def edge_lines(rb):
    return {'W':LineString([(rb[0],rb[1]),(rb[0],rb[3])]),'E':LineString([(rb[2],rb[1]),(rb[2],rb[3])]),
            'S(front,-y)':LineString([(rb[0],rb[1]),(rb[2],rb[1])]),'N(rear,+y)':LineString([(rb[0],rb[3]),(rb[2],rb[3])])}
def ncomp(g):
    if g is None or g.is_empty: return 0
    return len(g.geoms) if hasattr(g,'geoms') else 1
t4=[];t5=[]
for r in rooms:
    rid=r['room_id'];z0=r['z_m'];z1=z0+r['clear_height_m']
    rect=box(r['x_m'],r['y_m'],r['x_m']+r['width_m'],r['y_m']+r['depth_m'])
    rb=rect.bounds
    Hf=heights(z0,z1)
    per_z={}
    for z in Hf:
        gs=[]
        for n,p in PARTS.items():
            if p['fam'] not in('RIB','MULL','ATRIUM') or not bbox_hits(n,rb[0],rb[1],rb[2],rb[3],z,z): continue
            s,l=geom(n,z)
            for g in (s,l):
                if g is not None and g.intersects(rect): gs.append(g.intersection(rect))
        if gs:
            u=unary_union(gs)
            if not u.is_empty: per_z[z]=u
    rec=dict(room_id=rid,level_id=r['level_id'],n_heights=len(Hf),n_heights_with_obstacle=len(per_z),
        intruding_parts=sorted({x['part'] for x in t1 if x['room_id']==rid and x['family']!='ENCL'}),cap_sweep={})
    # splitting at each height (rib/mullion/atrium family), r=0 and capsule-eroded
    split_hts=[];split_by_d={str(d_):[] for d_ in SWEEP}
    for z,g in per_z.items():
        free=rect.difference(g.buffer(0))
        pieces=[f for f in (free.geoms if hasattr(free,'geoms') else [free]) if f.area>1e-3]
        if len(pieces)>1: split_hts.append((float(z),[round(f.area,2) for f in pieces]))
        for d_ in SWEEP:
            fr=rect.buffer(-d_/2).difference(g.buffer(d_/2))
            pc=[f for f in (fr.geoms if hasattr(fr,'geoms') else [fr]) if f.area>1e-3]
            if len(pc)>1: split_by_d[str(d_)].append(float(z))
    t5.append(dict(room_id=rid,intruding_parts=rec['intruding_parts'],n_heights_with_obstacle=len(per_z),n_heights_split_raw=len(split_hts),split_examples_raw=split_hts[:3],
        capsule_split_heights_count={k:len(v) for k,v in split_by_d.items()}))
    env=unary_union(list(per_z.values())) if per_z else None
    for d_ in SWEEP:
        if env is None:
            rec['cap_sweep'][str(d_)]=dict(obstacle=False);continue
        base=rect.buffer(-d_/2);free=base.difference(env.buffer(d_/2))
        gaps={nm:round(env.distance(ln),3) for nm,ln in edge_lines(rb).items()}
        rec['cap_sweep'][str(d_)]=dict(obstacle=True,components_after=ncomp(free),navigable_area_m2=round(free.area,3),baseline_area_m2=round(base.area,3),
            lost_area_m2=round(base.area-free.area,3),edge_gaps_m=gaps,edges_with_gap_below_d=[nm for nm,g in gaps.items() if g<d_])
    t4.append(rec)
json.dump(t4,open(OUT+'task4b_capsule_sweep_all_rooms.json','w'),indent=1)
json.dump(t5,open(OUT+'task5_room_splits.json','w'),indent=1)
print('rooms with any rib/mull/atrium obstacle in room:',[x['room_id'] for x in t5 if x['n_heights_with_obstacle']])
print('rooms split raw:',[ (x['room_id'],x['n_heights_split_raw']) for x in t5 if x['n_heights_split_raw']])
print('rooms capsule-split:',[ (x['room_id'],x['capsule_split_heights_count']) for x in t5 if any(x['capsule_split_heights_count'].values())])
for x in t4:
    if x['n_heights_with_obstacle']: print(json.dumps(x))
