"""Check proposed schedule references and bounding boxes; never mutates derived files.

These checks are not mesh sweeps, lift/stair verification or engine acceptance.
"""
from pathlib import Path
import hashlib
import json
import math

HERE = Path(__file__).resolve().parent

def read(path):
    return json.loads(path.read_text())

def overlap(a, b):
    return a[0] < b[2] - 1e-8 and b[0] < a[2] - 1e-8 and a[1] < b[3] - 1e-8 and b[1] < a[3] - 1e-8

def inside(a, b):
    return a[0] >= b[0] - 1e-8 and a[1] >= b[1] - 1e-8 and a[2] <= b[2] + 1e-8 and a[3] <= b[3] + 1e-8

def main():
    contract = read(HERE / 'BUILDING_DIMENSIONS.json')
    rooms = {r['room_id']: r for r in read(HERE / 'ROOM_SCHEDULE.json')['rooms']}
    route = read(HERE / 'ROUTE_AND_FURNISHING.json')
    props = {p['id']: p for p in read(HERE.parent / 'materials/prop_bill.json')['props']}
    materials = {m['id'] for m in read(HERE.parent / 'materials/material_library.json')['materials']}
    errors = []
    ids = set()
    for p in route['placements']:
        pid = p['instance_id']
        if pid in ids:
            errors.append(f'duplicate instance {pid}')
        ids.add(pid)
        r = rooms[p['room_id']]
        if not inside(p['aabb_xy_m'], r['clear_bounds_m']):
            errors.append(f'{pid} exceeds room clear bounds')
        if abs(p['position_m'][2] - r['floor_elevation_m']) > 1e-8:
            errors.append(f'{pid} has wrong floor elevation')
        if p['height_m'] > r['clear_height_m']:
            errors.append(f'{pid} exceeds room clear height')
        d = props[p['prop_id']]['dimensions_m']
        theta = math.radians(p['yaw_degrees'])
        dx = abs(d['width_x'] * math.cos(theta)) + abs(d['depth_y'] * math.sin(theta))
        dy = abs(d['width_x'] * math.sin(theta)) + abs(d['depth_y'] * math.cos(theta))
        a = p['aabb_xy_m']
        if abs(a[2] - a[0] - dx) > 1e-8 or abs(a[3] - a[1] - dy) > 1e-8:
            errors.append(f'{pid} bounding box disagrees with prop dimensions/yaw')
        for z in route['no_furniture_zones']:
            if z['room_id'] == p['room_id'] and overlap(a, z['bounds_xy_m']):
                errors.append(f'{pid} overlaps {z["id"]}')
        for core in contract['geometry']['cores']:
            if core['z_base_m'] <= p['position_m'][2] < core['z_top_m']:
                xs, ys = zip(*core['footprint'])
                if overlap(a, [min(xs), min(ys), max(xs), max(ys)]):
                    errors.append(f'{pid} overlaps {core["id"]}')
    ps = route['placements']
    for i, a in enumerate(ps):
        for b in ps[i + 1:]:
            if a['position_m'][2] == b['position_m'][2] and overlap(a['aabb_xy_m'], b['aabb_xy_m']):
                errors.append(f'{a["instance_id"]} overlaps {b["instance_id"]}')
    for r in rooms.values():
        for mid in r['material_keys']:
            if mid not in materials:
                errors.append(f'{r["room_id"]} unresolved material {mid}')
    for a in read(HERE / 'MATERIAL_ASSIGNMENTS.json')['assignments']:
        if a['material_id'] not in materials:
            errors.append(f'unresolved material {a["material_id"]}')
    digest = hashlib.sha256((HERE / 'BUILDING_DIMENSIONS.json').read_bytes()).hexdigest()
    if digest != route['contract_file_sha256']:
        errors.append('route references a different contract hash')
    out = dict(status='PASS' if not errors else 'FAIL', contract_sha256=digest,
               rooms=len(rooms), proposed_prop_instances=len(ps), distinct_prop_types=len({p['prop_id'] for p in ps}),
               no_furniture_zones=len(route['no_furniture_zones']), errors=errors,
               checks=['Prop ID and dimensions/yaw references', 'Host clear bounds and floor/ceiling height',
                       'No overlap with named keep-clear zones, solid core proxies or other proposed prop AABBs',
                       'Shared material IDs resolve', 'Route schedule contract hash'],
               limits=['Bounding-box schedule checks only; actual prop meshes are not delivered here.',
                       'The proposed path polyline and opening-center probes do not constitute a swept player or camera test.',
                       'CORE_L is solid: the ground-to-L19 vertical connection remains BLOCKED.',
                       'No door-swing, lift/stair behavior, accessibility/egress compliance or Unreal acceptance is claimed.'])
    (HERE / 'FURNISHING_CHECK.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps(out, indent=2))
    return int(bool(errors))

if __name__ == '__main__':
    raise SystemExit(main())
