"""Derive supplemental route, proposed furnishing placements and review diagrams.

Does not modify the geometry contract or the toolchain-owned derived directory.
"""
from pathlib import Path
import json,csv,hashlib,html

HERE=Path(__file__).resolve().parent
def write(name,data): (HERE/name).write_text(json.dumps(data,indent=2,ensure_ascii=False)+'\n')
contract=json.loads((HERE/'BUILDING_DIMENSIONS.json').read_text())
rooms=json.loads((HERE/'ROOM_SCHEDULE.json').read_text())['rooms']
lib=json.loads((HERE.parent/'materials/material_library.json').read_text())
props={p['id']:p for p in json.loads((HERE.parent/'materials/prop_bill.json').read_text())['props']}
source_sha=hashlib.sha256((HERE/'BUILDING_DIMENSIONS.json').read_bytes()).hexdigest()

routes=[
 dict(id='ROUTE-GROUND',state='horizontal layout proposed; source openings and slab exist',points_m=[[-35,-22,0],[-30,-17,0],[-30,2,0],[-38,4,0]],minimum_clear_width_m=3.0,ends_at='Before solid CORE_L proxy; vertical transition cannot be traversed'),
 dict(id='ROUTE-VERTICAL',state='BLOCKED / reservation only',points_m=[[-38,6,0],[-38,6,88]],minimum_clear_width_m=None,ends_at='Lift/stair design and behavior must replace solid core proxy; do not infer traversal from line'),
 dict(id='ROUTE-GALLERY',state='horizontal layout proposed; paired physical gallery portals exist',points_m=[[-38,4,88],[-30,0,88],[-20,0,88],[20,0,88],[26,0,88],[29,-4,88],[29,-17.5,88],[44,-17.5,88]],minimum_clear_width_m=3.0,ends_at='Front receiving overlook; return through same gallery/left core when implemented')]
zones=[
 dict(id='CLEAR-LOBBY',room_id='SP-L00-LOBBY',bounds_xy_m=[-32,-20,-28,4],purpose='Main arrival route; do not furnish'),
 dict(id='CLEAR-CORE-APPROACH',room_id='SP-L00-LOBBY',bounds_xy_m=[-40,2,-28,5.5],purpose='Turn toward future left lift interface'),
 dict(id='CLEAR-GALLERY',room_id='SP-L19-GALLERY',bounds_xy_m=[-20,-2,20,2],purpose='Four-metre central crossing lane'),
 dict(id='CLEAR-RECEIVING-ARRIVAL',room_id='SP-L19-RECEIVING',bounds_xy_m=[20,-6,29,6],purpose='Receiving portal/arrival strip'),
 dict(id='CLEAR-RECEIVING-LINK',room_id='SP-L19-RECEIVING',bounds_xy_m=[27.5,-19,30.5,1.5],purpose='Arrival to perimeter overlook'),
 dict(id='CLEAR-RECEIVING-PERIMETER',room_id='SP-L19-RECEIVING',bounds_xy_m=[20.35,-19.65,53.65,-16],purpose='Unfurnished front glazing perimeter')]
placements=[]
def place(pid,room,xy,yaw=0):
 p=props[pid]; d=p['dimensions_m']; w,h=d['width_x'],d['depth_y']
 if abs(yaw)%180==90:w,h=h,w
 z=0 if room=='SP-L00-LOBBY' else 88
 placements.append(dict(instance_id=f'SP-PROP-{len(placements)+1:03d}',prop_id=pid,room_id=room,position_m=[*xy,z],yaw_degrees=yaw,front_convention='Prop +Y rotated by yaw about local +Z',aabb_xy_m=[xy[0]-w/2,xy[1]-h/2,xy[0]+w/2,xy[1]+h/2],height_m=d['height_z'],state='Proposed bounding box only; prop geometry/material assignment and engine collision not verified'))
place('CK_PROP_P001','SP-L00-LOBBY',[-45,-5],180)
place('CK_PROP_P003','SP-L00-LOBBY',[-23,-10])
place('CK_PROP_P004','SP-L00-LOBBY',[-26,-7],180)
place('CK_PROP_P005','SP-L00-LOBBY',[-23,-7.5])
place('CK_PROP_P008','SP-L00-LOBBY',[-49,-16])
place('CK_PROP_P008','SP-L00-LOBBY',[-21,-17])
place('CK_PROP_P007','SP-L19-GALLERY',[-10,4.4],180)
place('CK_PROP_P007','SP-L19-GALLERY',[10,-4.4])
place('CK_PROP_P008','SP-L19-GALLERY',[-15,4.4])
place('CK_PROP_P008','SP-L19-GALLERY',[15,-4.4])
for x in [35,45]:
 place('CK_PROP_P003','SP-L19-RECEIVING',[x,-11])
 place('CK_PROP_P004','SP-L19-RECEIVING',[x-1.8,-6],180)
 place('CK_PROP_P004','SP-L19-RECEIVING',[x+1.8,-6],180)
 place('CK_PROP_P005','SP-L19-RECEIVING',[x,-8.5])
place('CK_PROP_P008','SP-L19-RECEIVING',[50,-14])
write('ROUTE_AND_FURNISHING.json',dict(asset_id=contract['asset_id'],revision=contract['contract_revision'],contract_file_sha256=source_sha,status='PROPOSED_LAYOUT_NOT_FULLY_TRAVERSABLE',routes=routes,no_furniture_zones=zones,prop_source='../materials/prop_bill.json',placements=placements,limitations=['Solid core proxies mean the vertical route is not traversable.','AABB checks do not test actual meshes, door swing, moving cameras, lift operation or fire/egress compliance.','Only a small furnishing subset is placed; other shared bill entries remain unplaced design choices.']))
assignment=[dict(surface='Lobby, landing, gallery and receiving floor finish',material_id='CK_MAT_002_STONE_HONED',implementation='Proposed finish over slabs; no new offset geometry implied'),dict(surface='Exterior mineral piers, blade/haunch skin and low arcade',material_id='CK_MAT_001_MINERAL_IVORY',implementation='Curved skin/haunch not yet authored'),dict(surface='Glazing frames and selected trim',material_id='CK_MAT_004_BRONZE_CHAMPAGNE',implementation='Frames not yet modeled; avoid total metallic walls'),dict(surface='Window/glazing openings',material_id='CK_MAT_005_GLASS_LAGOON',implementation='Glazing geometry exists; finished PBR mapping remains proposed'),dict(surface='Interior soffits and walls',material_id='CK_MAT_011_PLASTER_WARM',implementation='Neutral fallback OBJ materials are not automatically replaced'),dict(surface='Desk accents, lounge furniture and gallery benches',material_id='CK_MAT_006_TIMBER_WARM',implementation='Props specification only'),dict(surface='Sofas and lounge chairs',material_id='CK_MAT_007_LINEN_PALE',implementation='Props specification only'),dict(surface='Ground-gap paving',material_id='CK_MAT_003_STONE_EXTERIOR',implementation='Local apron geometry exists; no accepted site transform')]
write('MATERIAL_ASSIGNMENTS.json',dict(asset_id=contract['asset_id'],revision=contract['contract_revision'],status='PROPOSED_FINISH_ASSIGNMENTS',library='../materials/material_library.json',finish_application='../materials/finish_application.json',assignments=assignment,visual_limits=['The generated lounge concept has glossy stone and curved facade/columns beyond the orthogonal candidate. It is appearance guidance, not a same-model view.','Actual rendered OBJ currently uses technical category materials from toolchain; this schedule does not claim finished PBR assignment.']))
issues=[
 ('SP-I01','blocker','Full vertical circulation is not implemented','CORE_L/CORE_R are solid proxies. Author actual shaft/cabin/doors, switchback stair flights and landings; verify continuous route.','tooling and asset author'),
 ('SP-I02','blocker','Blade identity is not resolved by the blockout','Replace extruded upper proxies with the catalog asymmetric sculptural forms; preserve controlled bridge portals and update every drawing/view.','asset author / creative review'),
 ('SP-I03','decision','H1 and scale are working proposals','Creator selection remains unrecorded; numeric values are authored choices, not measurements.','Legend'),
 ('SP-I04','blocker_for_site_placement','Parcel/frame/entrance orientation unknown','Retain map transform, placement ID and district frame null. Local apron is not an accepted world connection.','district/Quik'),
 ('SP-I05','blocker','Bridge support, movement and roof build-up unresolved','One 40 m enclosed span needs authored bearing/haunch and loading intent; planting is a reservation, not structural verification.','asset author / technical review'),
 ('SP-I06','not_tested','Actual player, camera and Unreal checks','Pilot capsule defaults support analytical opening checks only. Import/collision/materials/lift/stair/performance need observed engine evidence.','Quik'),
 ('SP-I07','design_gap','Appearance and derived geometry differ','Existing concepts and the new receiving-lounge image include curved skins/columns not present in the orthogonal candidate. Neutral same-input renders govern current geometry.','asset author / root image reviewer'),
 ('SP-I08','design_gap','Props and materials are partial','Proposed placements use shared bounding boxes; detailed meshes, lighting, UVs, actual materials, LODs and collision are not delivered by the source schedule.','materials/asset author')]
write('ISSUES.json',dict(asset_id=contract['asset_id'],revision=contract['contract_revision'],design_ready=False,build_ready=False,engine_verified=False,issues=[dict(id=i,severity=s,title=t,action=a,owner=o,status='open') for i,s,t,a,o in issues]))
write('VIEW_MATRIX.json',dict(asset_id=contract['asset_id'],revision=contract['contract_revision'],views=[
 dict(role='Overall exterior',existing='docs/crown-key-design/R01/PI-BLD-0002-V01/media/split-exterior-r01.webp',status='existing appearance concept; not measured'),
 dict(role='Bridge detail',existing='docs/crown-key-design/R01/PI-BLD-0002-V01/media/split-bridge-r01.webp',status='existing appearance concept; underside curvature not modeled'),
 dict(role='Lobby',existing='docs/crown-key-design/R01/PI-BLD-0002-V01/media/split-lobby-r01.webp',status='existing appearance concept; compare with SP-CAM-LOBBY'),
 dict(role='Gallery',existing='docs/crown-key-design/R01/PI-BLD-0002-V01/media/split-gallery-r01.webp',status='existing appearance concept; compare with SP-CAM-GALLERY'),
 dict(role='Receiving lounge',existing='../images/split-receiving-lounge-r01.webp',status='new root-generated appearance concept; curved/glossy deviations disclosed; see image operator record'),
 dict(role='Rear/opposite side',existing=None,status='neutral same-input rear view supplied by toolchain; finished coherent blade treatment still missing'),
 dict(role='Entrance close-up',existing=None,status='door datum/opening authored; targeted appearance detail remains missing'),
 dict(role='Receiving reverse / exit',existing=None,status='SP-CAM-RECEIVING-REVERSE defines neutral evidence; finished appearance variant remains missing')],generation_rule='Use same authored model and saved camera for geometric claims. Site background remains neutral until placement known.'))
with (HERE/'ROOM_SCHEDULE.csv').open('w',newline='') as f:
 w=csv.writer(f); w.writerow(['room_id','name','level_id','floor_elevation_m','clear_height_m','clear_bounds_xy_m','state'])
 for r in rooms:w.writerow([r['room_id'],r['name'],r['level_id'],r['floor_elevation_m'],r['clear_height_m'],json.dumps(r['clear_bounds_m']),'proposed; see core/route holds'])

# Compact two-plan review diagram uses exact proposed plan geometry and prop bounds.
W,H=1400,1200; out=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}"><rect width="100%" height="100%" fill="#f6f4ee"/>']
def txt(x,y,t,size=14,color='#162e3a',weight='normal'):out.append(f'<text x="{x}" y="{y}" font-family="Arial,sans-serif" font-size="{size}" fill="{color}" font-weight="{weight}">{html.escape(t)}</text>')
txt(40,40,'SPLIT COMPLEX · H1 C01 PROPOSED LOCAL-SPACE PLAN',25,weight='bold')
txt(40,67,'PI-BLD-0002-V01 · metres · +X right / +Y rear / front −Y · site transform unknown',15)
txt(40,92,'Zoning diagram from source geometry; walls/openings omitted. Props are bounding boxes. Use derived keyed plans for openings.',15,'#a23c2e')
S=9.5
for iz,(level,z,oy,title) in enumerate([('L00',0,170,'GROUND · L00 +0.0m'),('L19',88,670,'GALLERY / RECEIVING · L19 +88.0m')]):
 ox=75
 def pt(x,y):return (ox+(x+56)*S,oy+(y+26)*S)
 txt(40,oy-25,title,20,weight='bold')
 for m in contract['geometry']['masses']:
  if m['z_base_m']<=z<m['z_top_m'] and (m['shell']=='hollow' or m['kind']=='canopy'):
   points=' '.join(f'{a:.1f},{b:.1f}' for a,b in [pt(*v) for v in m['footprint']]);out.append(f'<polygon points="{points}" fill="#dce7e9" stroke="#1a3d50" stroke-width="2"/>')
 for c in contract['geometry']['cores']:
  p0=pt(*c['footprint'][0]);p2=pt(*c['footprint'][2]);out.append(f'<rect x="{p0[0]}" y="{p0[1]}" width="{p2[0]-p0[0]}" height="{p2[1]-p0[1]}" fill="#d7aca4" stroke="#a23c2e"/>');txt(p0[0]+4,p0[1]+18,c['id'],12,'#802a20')
 for c in zones:
  rr=next(r for r in rooms if r['room_id']==c['room_id'])
  if rr['level_id']!=level:continue
  x0,y0,x1,y1=c['bounds_xy_m'];p0=pt(x0,y0);p2=pt(x1,y1);out.append(f'<rect x="{p0[0]}" y="{p0[1]}" width="{p2[0]-p0[0]}" height="{p2[1]-p0[1]}" fill="#e7c67a" fill-opacity=".45" stroke="#b58722" stroke-dasharray="5 4"/>')
 for p in placements:
  if p['position_m'][2]!=z:continue
  x0,y0,x1,y1=p['aabb_xy_m'];p0=pt(x0,y0);p2=pt(x1,y1);out.append(f'<rect x="{p0[0]}" y="{p0[1]}" width="{p2[0]-p0[0]}" height="{p2[1]-p0[1]}" fill="#a39579" stroke="#554e40"/>')
 for rt in routes:
  if rt['id']=='ROUTE-VERTICAL' or rt['points_m'][0][2]!=z:continue
  points=' '.join(f'{a:.1f},{b:.1f}' for a,b in [pt(v[0],v[1]) for v in rt['points_m']]);out.append(f'<polyline points="{points}" fill="none" stroke="#1d6e79" stroke-width="3" stroke-dasharray="10 4"/>')
 labels=[(-49,-19,'Lobby 33.3 × 39.3 clear envelope'),(-16,-8,'Open gap / proposed paving'),(21,-21,'Right base: undeveloped interior')] if level=='L00' else [(-47,-15,'Left landing'),(-18,-8,'Gallery: 40m span / 11.3m clear width'),(29,-15,'Lounge furnishing zone 21 × 22m')]
 for x,y,t in labels:xx,yy=pt(x,y);txt(xx,yy,t,12)
 txt(1175,oy+40,'Front −Y ↑',16,weight='bold');txt(1175,oy+67,'X → local right',13)
 if level=='L19':
  txt(1175,oy+100,'Gallery clear:6.0m',13);txt(1175,oy+122,'Landing clear:6.6m',13);txt(1175,oy+144,'Portal clear:4.2 × 3.2m',13)
txt(40,1170,'PROPOSED DESIGN • NOT BUILD-READY • NO ENGINE TEST • blue route stops before solid core; no lift/stair behavior is modeled',15,'#a23c2e',weight='bold')
out.append('</svg>');(HERE/'PLAYABLE_SLICE_PLAN.svg').write_text(''.join(out))
