
# ---------------- 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))
