import json,csv,collections
O='C:/q2/out/C_ribs/'
PUBF='C:/q2/r/production/handoffs/quik/2026-10-16/crown-landmark/FIT-COVERAGE/C02/C02_FIT_COVERAGE.csv'
pub={r['room_id']:r for r in csv.DictReader(open(PUBF))}
t1=json.load(open(O+'task1_room_intrusions.json'));near=json.load(open(O+'task1b_nearest_by_room.json'))
t3=json.load(open(O+'task3_doors.json'));t4=json.load(open(O+'task4b_capsule_sweep_all_rooms.json'));t5=json.load(open(O+'task5_room_splits.json'))
L=json.load(open('C:/q2/layout.json'))
SW=['0.6','0.7','0.8','1.0']
rooms=[]
for r in L['rooms']:
    rid=r['room_id']
    p=json.loads(pub[rid]['rib_intrusions']) if pub[rid]['rib_intrusions'] else {}
    mine=[x for x in t1 if x['room_id']==rid and x['family'] in('RIB','MULL','ATRIUM')]
    encl=[x['part'] for x in t1 if x['room_id']==rid and x['family']=='ENCL']
    nn={f:next(x for x in near if x['room_id']==rid and x['family']==f) for f in('RIB','MULL','ATRIUM')}
    mind=[(nn[f]['nearest_dist_m'],f,nn[f]['nearest_part']) for f in nn if nn[f]['nearest_dist_m'] is not None]
    md=min(mind) if mind else (None,None,None)
    s5=next(x for x in t5 if x['room_id']==rid)
    row=dict(room_id=rid,level_id=r['level_id'],published_rib_intrusions=json.dumps(p),
        my_rib_family_intruding=';'.join(x['part'] for x in mine if x['family']=='RIB'),
        my_mullion_band_intruding=';'.join(x['part'] for x in mine if x['family']=='MULL'),
        my_atrium_family_intruding=';'.join(x['part'] for x in mine if x['family']=='ATRIUM'),
        enclosure_parts_cutting_room_context=';'.join(encl),
        nearest_rib_family_m=nn['RIB']['nearest_dist_m'],nearest_rib_part=nn['RIB']['nearest_part'],
        nearest_mullion_band_m=nn['MULL']['nearest_dist_m'],nearest_mullion_part=nn['MULL']['nearest_part'],
        nearest_atrium_family_m=nn['ATRIUM']['nearest_dist_m'],nearest_atrium_part=nn['ATRIUM']['nearest_part'],
        min_gap_any_family_m=md[0],min_gap_family=md[1],min_gap_part=md[2],
        agree_with_published=(bool(p)==bool([x for x in mine if x['family']=='RIB'])),
        split_heights_raw=s5['n_heights_split_raw'],capsule_split=json.dumps(s5['capsule_split_heights_count']))
    for d in SW:
        row['gap_below_%s'%d]=(md[0] is not None and md[0]<float(d)) or any(x['room_id']==rid and x['cap_sweep'].get(d,{}).get('edges_with_gap_below_d') for x in t4)
    rooms.append(row)
with open(O+'rooms_81.csv','w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rooms[0]));w.writeheader();w.writerows(rooms)
with open(O+'doors_102.csv','w',newline='') as f:
    keys=[]
    for r in t3:
        for k in r:
            if k not in keys: keys.append(k)
    w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(t3)
F=[]
def add(**k): F.append(k)
add(id='F1',task=1,label='measured',subject='L03-RM001 / Rib_R1',finding='Rib_R1 solid enters the room from z=22.00 (4.00 m above L03 floor z=18) to ceiling z=23.40; slice area in room 0.085 m2 @22.25, 0.55 @22.75, 1.19 @23.25, 1.40 @23.39 (max); plan envelope 1.417 m2, x -38.00..-37.12, y -40.42..-37.89; max depth from room edge 0.873 m at ceiling (0.816 m at z=23.3). Intrusion is overhead only (4.0-5.4 m above floor). Nearest door L03-D001 is 22.2 m away; no door within 1.0 m.')
add(id='F2',task=1,label='measured',subject='all 81 rooms',finding='Only L03-RM001 has any Rib_/Gold_inner_/Crown_glass_/Mullion_/Storey_band_/atrium-gold/amber-skin/cap solid or surface inside its rectangle and z range (fine sweep 0.25 m from z_bottom+0.1 to z_top-0.1 plus the three requested heights). Tower rooms L25/L26: nothing inside.')
add(id='F3',task=2,label='measured',subject='published rib_intrusions column',finding='Published: 1 room, L03-RM001 {Rib_R1: 26 samples}; all other 80 rooms {}. Mine: same 1 room, same part. Room-list agreement 81/81, 0 disagreements. Published test names only Rib_*; widening to Gold_inner/Mullion/Storey_band/atrium parts adds no rooms. Published value is a surface-sample count, not an area; mine is slice area 1.40 m2 max.')
add(id='F4',task=2,label='measured',subject='3-height scheme',finding='For L03-RM001 the three requested heights (z_bottom+0.1, mid, z_top-0.1) detect Rib_R1 only at z_top-0.1=23.3 (area 1.19 m2); at 18.1 and 20.7 it is absent because the rib enters at z=22.0.')
add(id='F5',task=3,label='measured',subject='102 doors',finding='No door is blocked or narrowed by a rib/mullion/storey band. Nearest Rib_/Gold_inner_ to any door: 7.884 m (L26-D011, Gold_inner_R4), then 9.903 (L25-D006, Rib_R6). Nearest mullion/storey band: 4.512 m (L26-D010, L26-D011, Storey_band_18), 5.164 (L26-D004). Nearest atrium/crossed-gold/amber skin: 5.364 (L26-D004). No door has a rib-family part within 1.0 m. Mullions/bands do not exist below z=53.9, so L00-L03 doors have none in range.')
add(id='F6',task=3,label='measured',subject='L00-D001 (context, not rib/mullion)',finding='Portal door L00-D001 (x=0, y=-52, 8 m x 4.5 m): Podium_wall_1 front wall plane at y=-52.4 (x -39.2..27.2, z 0.2..17.35, 16-triangle box, no portal cut-out) lies 0.4 m outside the door line across the full 8 m width. Outside rib scope; recorded because the wall closes the portal as modelled.')
add(id='F7',task=4,label='measured',subject='L03-RM001 vs Rib_R1 shortfall',finding='Room x -38..-14, y -48..-24, z 18..23.4. Rib_R1 overlap on west edge: depth 0.873 m at ceiling. Minimum rigid shift of the room to clear all Rib_R1 solids over the full z range: +x 0.880 m (east); +y (rearward) 10.115 m; -y (frontward) 16.425 m; -x 30.005 m. A 4.8 m rearward shift (README relocation figure) still overlaps by 1.417 m2. Room area 576 m2; 574.58 m2 left after removing the envelope, 1 piece.')
add(id='F8',task=4,label='measured',subject='L25/L26 rib clearance',finding='Rib family is entirely outside all 32 tower rooms. Nearest Rib_/Gold_inner_ to a room rect: 2.256 m (L26-RM001 Rib_R5), 2.257 (L26-RM002 Rib_R6), 2.405 (L26-RM003 Rib_R1; L26-RM006 Rib_R2), 2.634 (L25-RM003 Rib_R6), 2.637 (L25-RM002 Rib_R5); other tower rooms 5.2 m or more, or none within 8 m. Closest of any rib/mullion/band/atrium-gold part: 1.456 m (L26-RM005 Front_atrium_gold_-1), 1.457 (L26-RM004 Front_atrium_gold_1), 1.505 (L26-RM005 Mullion_51), 1.613 (L26-RM004 Storey_band_18). Capsule sweep 0.6/0.7/0.8/1.0 m: no L25/L26 room has a gap below any value. Gap = plan distance part-to-room-rectangle edge (interpreted as clear width; the gap may lie outside the walkable envelope).')
add(id='F9',task=5,label='measured',subject='room splitting',finding='No rib/mullion/band/atrium part splits any room rectangle into disconnected pieces at any sampled height, raw or with capsule erosion 0.6-1.0 m. The Rib_R1 notch in L03-RM001 leaves one piece (574.58 of 576 m2).')
add(id='F10',task=1,label='measured',subject='context: other intersections (not rib/mullion)',finding='L00-RM001 (arrival atrium): Canopy_gold_edge_52 enters 0.17 m at z 5.1-7.35 (door L00-D001 within 1 m). L00-RM003: T1_front_arch_1 plan 2.86 m2 (x -37.54..-36.24, y -38.1..-35.9), up to 1.76 m from room edge, z 0.1-5.3, nearest door 13.2 m. L03-RM001: Podium_wall_2 surface at y=-44.4 crosses the full 24 m width, 3.6 m inside the room edge (room strip y -48..-44.4 lies outside the wall line). Front_amber_atrium_skin passes 0.6 m from the L00-RM001 front edge.')
json.dump(F,open(O+'findings.json','w'),indent=1)
with open(O+'findings.csv','w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=['id','task','label','subject','finding']);w.writeheader();w.writerows(F)
print(collections.Counter(r['agree_with_published'] for r in rooms))
print([r['room_id'] for r in rooms if r['gap_below_1.0']])
