"""Sample proposed L00 routes against the shared PR51 geometry analysis.

This is an author-side static check, not collision, navigation or engine acceptance.
Run from any folder. Outputs only FURNISHED_ROUTE_CHECK.json in this package.
"""
from pathlib import Path
import hashlib
import json
import math
import sys

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'tooling/source-cache/tools/contracts'))
import contract

raw = (HERE / 'BUILDING_DIMENSIONS.json').read_bytes()
source = json.loads(raw)
analysis = contract.analyse(source)
assert analysis['result'] == 'COMPLETE', analysis
geo = analysis['derived']
route_source = json.loads((HERE / 'ROUTES.json').read_text())
radius = 0.55
angles = [2 * math.pi * i / 24 for i in range(24)]
offsets = [(0, 0)] + [(radius * math.cos(a), radius * math.sin(a)) for a in angles]


def contains(p, poly):
    return contract.point_in_polygon(p, poly)


def collisions(p, z):
    hits = []
    for m in geo['masses']:
        if not m['z0'] <= z <= m['z1'] or not contains(p, m['footprint']):
            continue
        if m['shell'] == 'solid':
            hits.append(m['id'])
        elif not contains(p, m['inner']):
            open_cut = any(o['host'] == m['id'] and o['cut'] and o['z0'] <= z <= o['z1'] and contains(p, o['cut_band']) for o in geo['openings'])
            if not open_cut:
                hits.append(m['id'] + ':wall')
    for o in geo['openings']:
        if o.get('glazing_band') and o['z0'] <= z <= o['z1'] and contains(p, o['glazing_band']):
            hits.append(o['id'] + ':glazing')
    for c in geo['cores']:
        if c['z0'] <= z <= c['z1'] and contains(p, c['footprint']):
            hits.append(c['id'])
    return hits


def floor(p):
    return any((m['shell'] == 'hollow' and abs(m['z0']) < 1e-6 or m['shell'] == 'solid' and abs(m['z1']) < 1e-6) and contains(p, m['footprint']) for m in geo['masses'])


results = []
for route in route_source['routes']:
    failures, centres = [], 0
    for a, b in zip(route['points_m'], route['points_m'][1:]):
        count = max(1, math.ceil(math.dist(a, b) / .1))
        for n in range(count + 1):
            p = [a[k] + (b[k] - a[k]) * n / count for k in range(2)]
            centres += 1
            for dx, dy in offsets:
                q = [p[0] + dx, p[1] + dy]
                hit = sorted({h for z in [.15, .9, 1.8] for h in collisions(q, z)})
                if hit or not floor(q):
                    failures.append({'centre_xy_m': p, 'sample_xy_m': q, 'hits': hit, 'floor_present': floor(q)})
    results.append({'route_id': route['id'], 'result': 'PASS_SAMPLED' if not failures else 'FAIL', 'centre_samples': centres, 'failed_samples': len(failures), 'first_failures': failures[:10]})

report = {'asset_id': source['asset_id'], 'contract_revision': source['contract_revision'], 'contract_file_sha256': hashlib.sha256(raw).hexdigest(), 'result': 'PASS_SAMPLED' if all(x['failed_samples'] == 0 for x in results) else 'FAIL', 'method': {'source': 'existing PR51 contract.analyse and point_in_polygon', 'centre_step_max_m': .1, 'radial_samples': 24, 'radius_including_proposed_margin_m': radius, 'body_sample_heights_m': [.15, .9, 1.8], 'floor_datum_m': 0}, 'routes': results, 'limits': ['Finite sample test, not continuous collision proof.', 'Proposed body dimensions; actual engine/player/camera unknown.', 'No moving door, physics, NavMesh, performance or human egress check.', 'Upper envelope/core/terraces are deliberately outside playable route.']}
(HERE / 'FURNISHED_ROUTE_CHECK.json').write_text(json.dumps(report, indent=2) + '\n')
print(report['result'], [(r['route_id'], r['failed_samples']) for r in results])
raise SystemExit(0 if report['result'] == 'PASS_SAMPLED' else 1)
