import json,csv,numpy as np,collections
from rc import *
L=json.load(open('C:/q2/layout.json'))
rooms=L['rooms']
pts=[];meta=[]
for r in rooms:
    x0,y0,w,d=r['x_m'],r['y_m'],r['width_m'],r['depth_m'];z=r['z_m']
    P={'centre':(x0+w/2,y0+d/2)}
    for k,(cx,cy,sx,sy) in {'c_SW':(x0,y0,1,1),'c_SE':(x0+w,y0,-1,1),'c_NW':(x0,y0+d,1,-1),'c_NE':(x0+w,y0+d,-1,-1)}.items():
        P[k]=(cx+sx*min(1.5,w/2),cy+sy*min(1.5,d/2))   # corner +1.5 m inward (clamped to room half-size)
    for k,(x,y) in P.items():
        pts.append((x,y,z+1.5));meta.append((r['room_id'],r['level_id'],z,k,x,y))
O=np.array(pts);D=np.tile([0,0,-1.0],(len(O),1))
out=cast(O,D);H=flat(out,len(O))
rows=[]
for (rid,lv,z,k,x,y),h,o in zip(meta,H,O):
    # hits below origin (downward). origin is z+1.5. first hit:
    first=h[0] if h else None
    hz=None if first is None else o[2]-first[0]
    supp=None
    if first is not None:
        supp = abs(hz-z)<=0.05
    # also nearest hit that is within +-0.05 of nominal level
    atlevel=[(o[2]-t,n,dt,nz) for t,n,dt,nz in h if abs(o[2]-t-z)<=0.05]
    rows.append(dict(room=rid,level=lv,level_z=z,pt=k,x=round(x,2),y=round(y,2),first_part=first[1] if first else None,
        first_hit_z=None if hz is None else round(hz,3),first_front_facing=None if first is None else (first[2]<0),
        first_normal_z=None if first is None else round(first[3],2),
        floor_at_level=bool(atlevel),floor_part_at_level=atlevel[0][1] if atlevel else None,
        n_hits_below=len(h),all_hits=';'.join('%s@%.2f%s'%(n,o[2]-t,'F' if dt<0 else 'B') for t,n,dt,nz in h[:6])))
with open('walkable_rays.csv','w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0].keys()));w.writeheader();w.writerows(rows)
# per level summary
S={}
for lv in ['L00','L01','L02','L03','L25','L26']:
    rr=[r for r in rows if r['level']==lv]
    n=len(rr);sup=sum(r['floor_at_level'] for r in rr)
    fp=collections.Counter(r['first_part'] for r in rr);fh=collections.Counter(r['first_hit_z'] for r in rr)
    frontf=collections.Counter((r['floor_part_at_level'],r['first_front_facing']) for r in rr if r['floor_at_level'])
    rm=collections.defaultdict(list)
    for r in rr: rm[r['room']].append(r['floor_at_level'])
    sup_rooms_all=sum(all(v) for v in rm.values());sup_rooms_any=sum(any(v) for v in rm.values())
    S[lv]=dict(level_z=rr[0]['level_z'],rooms=len(rm),points=n,points_with_surface_at_level=sup,rooms_all_5_pts_supported=sup_rooms_all,rooms_any_pt_supported=sup_rooms_any,
        first_hit_parts=dict(fp),first_hit_z_values=dict((str(k),v) for k,v in fh.items()),floor_part_at_level_and_frontfacing=dict((str(k),v) for k,v in frontf.items()))
    print(lv,json.dumps(S[lv],indent=0)[:1500])
json.dump(S,open('walkable_summary.json','w'),indent=1)
# list rooms without support
bad=[r for r in rows if r['pt']=='centre' and not r['floor_at_level']]
print(len(bad),'room centres without surface at level z')
for r in bad[:60]: print(r['room'],r['level_z'],r['first_part'],r['first_hit_z'],r['all_hits'])
