#!/usr/bin/env python3
"""Independent exported-geometry audit. Does not import the model builder."""
from pathlib import Path
import csv
import hashlib
import json
import struct
import numpy as np

HERE = Path(__file__).resolve().parent
REPO = next(p for p in HERE.parents if (p / 'AGENTS.md').exists())
MODEL = HERE / 'MODEL'
PREFIX = 'PI-BLD-0001-V01_CrownLandmark_SHELL_C01'
LAYOUT = REPO / 'production/assets/buildings/PI-BLD-0001-V01/INT/R02/06_Handoff/EditableLayout/INTERIOR_LAYOUT.json'
EPS = 1e-5


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def read_glb(path):
    raw = path.read_bytes()
    magic, version, size = struct.unpack_from('<III', raw)
    assert (magic, version, size) == (0x46546C67, 2, len(raw)), 'Invalid GLB header'
    chunks, offset = {}, 12
    while offset < size:
        length, kind = struct.unpack_from('<II', raw, offset)
        chunks[kind] = raw[offset + 8:offset + 8 + length]
        offset += 8 + length
    doc = json.loads(chunks[0x4E4F534A])
    binary = chunks[0x004E4942]
    dtypes = {5120: 'i1', 5121: 'u1', 5122: '<i2', 5123: '<u2', 5125: '<u4', 5126: '<f4'}
    widths = {'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4}

    def accessor(index):
        a = doc['accessors'][index]
        assert 'sparse' not in a and not a.get('normalized'), 'Unsupported accessor'
        v = doc['bufferViews'][a['bufferView']]
        assert v.get('buffer', 0) == 0
        dtype = np.dtype(dtypes[a['componentType']])
        width = widths[a['type']]
        stride = v.get('byteStride', width * dtype.itemsize)
        start = v.get('byteOffset', 0) + a.get('byteOffset', 0)
        assert start + (a['count'] - 1) * stride + width * dtype.itemsize <= len(binary)
        return np.ndarray((a['count'], width), dtype=dtype, buffer=binary,
                          offset=start, strides=(stride, dtype.itemsize)).copy()

    result = {}
    active = doc['scenes'][doc.get('scene', 0)]['nodes']
    for idx in active:
        node = doc['nodes'][idx]
        assert not any(k in node for k in ['matrix', 'rotation', 'translation', 'scale', 'children']), 'Unexpected transformed/hierarchical node'
        mesh = doc['meshes'][node['mesh']]
        assert len(mesh['primitives']) == 1
        p = mesh['primitives'][0]
        assert p.get('mode', 4) == 4
        gltf_v = accessor(p['attributes']['POSITION']).astype(float)
        # glTF standard Y-up -> source Z-up. Verified independently against OBJ.
        v = gltf_v[:, [0, 2, 1]].copy()
        v[:, 1] *= -1
        f = accessor(p['indices']).reshape(-1, 3).astype(np.int64)
        normals = accessor(p['attributes']['NORMAL']).astype(float)
        name = node.get('name', mesh['name'])
        assert name not in result
        result[name] = {'v': v, 'f': f, 'normals': normals}
    return result


def read_obj(path):
    vertices, normals, objects = [], [], {}
    name = None
    for line in path.read_text().splitlines():
        parts = line.split()
        if not parts:
            continue
        if parts[0] == 'o':
            name = ' '.join(parts[1:])
            objects[name] = {'vertex_start': len(vertices), 'vertex_end': None, 'f': []}
        elif parts[0] == 'v':
            vertices.append([float(x) for x in parts[1:4]])
            objects[name]['vertex_end'] = len(vertices)
        elif parts[0] == 'vn':
            normals.append([float(x) for x in parts[1:4]])
        elif parts[0] == 'f':
            assert len(parts) == 4, 'Expected triangulated OBJ'
            ids = [int(x.split('/')[0]) for x in parts[1:]]
            objects[name]['f'].append([x - 1 if x > 0 else len(vertices) + x for x in ids])
    vertices = np.asarray(vertices)
    result = {}
    for name, obj in objects.items():
        start, end = obj['vertex_start'], obj['vertex_end']
        result[name] = {'v': vertices[start:end], 'f': np.asarray(obj['f'], dtype=np.int64) - start}
    assert np.isfinite(normals).all(), 'Nonfinite OBJ normals'
    return result


def cross2(a, b):
    return float(a[0] * b[1] - a[1] * b[0])


def point_segment(p, a, b):
    delta = b - a
    t = float(np.dot(p - a, delta) / np.dot(delta, delta))
    return float(np.linalg.norm(p - (a + np.clip(t, 0, 1) * delta)))


def inside(p, polygon):
    if any(point_segment(p, a, b) <= EPS for a, b in zip(polygon, np.roll(polygon, -1, axis=0))):
        return True
    hit = False
    for a, b in zip(polygon, np.roll(polygon, -1, axis=0)):
        if (a[1] > p[1]) != (b[1] > p[1]):
            x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1])
            if p[0] < x:
                hit = not hit
    return hit


def proper_cross(a, b, c, d):
    return cross2(b - a, c - a) * cross2(b - a, d - a) < -EPS**2 and cross2(d - c, a - c) * cross2(d - c, b - c) < -EPS**2


def section(mesh, z):
    """Intersect actual exported triangles with a horizontal plane; stitch segments."""
    edges, coords = set(), {}
    for tri in mesh['v'][mesh['f']]:
        signed = tri[:, 2] - z
        if np.all(signed > EPS) or np.all(signed < -EPS) or np.all(np.abs(signed) <= EPS):
            continue
        points = []
        for j in range(3):
            a, b = tri[j], tri[(j + 1) % 3]
            da, db = a[2] - z, b[2] - z
            if abs(da) <= EPS:
                points.append(a[:2])
            if da * db < 0 and abs(da) > EPS and abs(db) > EPS:
                points.append((a + (-da / (db - da)) * (b - a))[:2])
        unique = {}
        for point in points:
            key = tuple(np.rint(point / EPS).astype(np.int64))
            unique[key] = point
        if len(unique) == 2:
            keys = sorted(unique)
            edges.add(tuple(keys))
            coords.update(unique)
        elif len(unique) > 2:
            raise AssertionError('Ambiguous section triangle')
    graph = {}
    for a, b in edges:
        graph.setdefault(a, set()).add(b)
        graph.setdefault(b, set()).add(a)
    assert graph and all(len(v) == 2 for v in graph.values()), f'Nonclosed section at {z}'
    first = min(graph)
    loop, previous, current = [first], None, first
    while True:
        nxt = next(x for x in graph[current] if x != previous)
        if nxt == first:
            break
        assert nxt not in loop, 'Section self-loop'
        loop.append(nxt)
        previous, current = current, nxt
    assert len(loop) == len(graph), 'Multiple section loops need explicit resolution'
    return np.asarray([coords[k] for k in loop])


def rectangle_fit(rectangle, polygon):
    """Exact line-segment distances, corner inclusion and concavity crossing checks."""
    redges = list(zip(rectangle, np.roll(rectangle, -1, axis=0)))
    pedges = list(zip(polygon, np.roll(polygon, -1, axis=0)))
    corner_inside = [inside(c, polygon) for c in rectangle]
    corner_dist = [min(point_segment(c, a, b) for a, b in pedges) for c in rectangle]
    crosses = any(proper_cross(a, b, c, d) for a, b in redges for c, d in pedges)
    # A concave perimeter can intrude into a rectangle with all corners inside.
    intrusion = any(inside(c, rectangle) and min(point_segment(c, a, b) for a, b in redges) > EPS for c in polygon)
    contained = all(corner_inside) and not crosses and not intrusion
    distance = min(min(point_segment(a, c, d), point_segment(b, c, d),
                       point_segment(c, a, b), point_segment(d, a, b))
                   for a, b in redges for c, d in pedges)
    if crosses:
        distance = 0.0
    if contained:
        margin = distance
    else:
        outside = [dist for dist, ins in zip(corner_dist, corner_inside) if not ins]
        margin = -max(outside) if outside else -distance
    return {'contained': bool(contained), 'perimeter_margin_m': margin,
            'outside_corner_count': sum(not x for x in corner_inside),
            'boundary_crossing': crosses, 'concave_intrusion': intrusion}


def main():
    specpath = HERE / 'MODEL_SPEC.json'
    spec = json.loads(specpath.read_text())
    layout = json.loads(LAYOUT.read_text())
    glbpath, objpath = MODEL / (PREFIX + '.glb'), MODEL / (PREFIX + '.obj')
    glb, obj = read_glb(glbpath), read_obj(objpath)
    checks = []

    def check(name, actual, expected, tolerance=0.01):
        err = float(np.max(np.abs(np.asarray(actual) - np.asarray(expected))))
        checks.append({'check': name, 'actual': actual, 'expected': expected,
                       'tolerance_m': tolerance, 'max_error_m': err, 'pass': err <= tolerance})

    integrity = []
    assert set(glb) == set(obj), 'GLB/OBJ object sets differ'
    for name, mesh in glb.items():
        v, f = mesh['v'], mesh['f']
        bad = int(np.sum((f < 0) | (f >= len(v))))
        finite = bool(np.isfinite(v).all() and np.isfinite(mesh['normals']).all())
        area = np.linalg.norm(np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]]), axis=1) / 2 if not bad else np.array([0.0])
        zero = int(np.sum(area <= 1e-12))
        o = obj[name]
        obj_bad = int(np.sum((o['f'] < 0) | (o['f'] >= len(o['v']))))
        obj_area = np.linalg.norm(np.cross(o['v'][o['f'][:, 1]] - o['v'][o['f'][:, 0]], o['v'][o['f'][:, 2]] - o['v'][o['f'][:, 0]]), axis=1) / 2 if not obj_bad else np.array([0.0])
        obj_zero = int(np.sum(obj_area <= 1e-12))
        same_indices = bool(np.array_equal(f, o['f']))
        deviation = float(np.max(np.abs(v - o['v']))) if v.shape == o['v'].shape else None
        passed = finite and not bad and not zero and not obj_bad and not obj_zero and bool(np.isfinite(o['v']).all()) and same_indices and deviation is not None and deviation <= 2e-5
        integrity.append({'object': name, 'vertices': len(v), 'triangles': len(f), 'finite': finite,
                          'invalid_indices': bad, 'zero_area_triangles': zero, 'minimum_triangle_area_m2': float(area.min()),
                          'obj_invalid_indices': obj_bad, 'obj_zero_area_triangles': obj_zero,
                          'obj_indices_equal': same_indices, 'obj_max_coordinate_difference_m': deviation, 'pass': bool(passed)})
    allv = np.concatenate([m['v'] for m in glb.values()])
    check('height_above_finished_ground', float(allv[:, 2].max()), 240.0)
    foundation = glb['Foundation_160x120']['v']
    check('foundation_width_depth', np.ptp(foundation[:, :2], axis=0).tolist(), [160, 120])
    check('foundation_top_datum', float(foundation[:, 2].max()), 0.0)
    for n, target in enumerate(spec['targets']['podium_decks'], 1):
        mesh = glb[f'Deck_{n}_top_{target["z_m"]}m']['v']
        top = float(mesh[:, 2].max())
        topv = mesh[np.abs(mesh[:, 2] - top) < EPS]
        check(f'deck_{n}_top_width_depth', [top, *np.ptp(topv[:, :2], axis=0).tolist()], [target['z_m'], target['width_m'], target['depth_m']])
    for rib in spec['targets']['principal_ribs']:
        v = glb['Rib_' + rib['id']]['v']
        tip = v[np.abs(v[:, 2] - v[:, 2].max()) < EPS]
        check(rib['id'] + '_tip_center_xyz', tip.mean(axis=0).tolist(), [*rib['crown_tip_xy_m'], rib['crown_tip_z_m']])
    references = []
    for ref in spec['references']:
        p = REPO / ref['path']
        actual = sha(p) if p.exists() else None
        references.append({'path': ref['path'], 'expected_sha256': ref['sha256'], 'actual_sha256': actual, 'pass': actual == ref['sha256']})
    targets_ref = next(x for x in spec['references'] if x['path'].endswith('DesignTargets.json'))
    targets_equal = json.loads((REPO / targets_ref['path']).read_text()) == spec['targets']
    sections, fits = {}, []
    allowance = float(spec['proposed']['assembly_allowance_m'])
    for room in layout['rooms']:
        if room['level_id'] not in ['L25', 'L26']:
            continue
        x, y, w, dep = (room[k] for k in ['x_m', 'y_m', 'width_m', 'depth_m'])
        rect = np.asarray([[x, y], [x + w, y], [x + w, y + dep], [x, y + dep]], float)
        for label, z in [('bottom', room['z_m']), ('top', room['z_m'] + room['clear_height_m'])]:
            key = f'{z:.6f}'
            if key not in sections:
                sections[key] = section(glb['Tower_curtainwall_skin'], z)
            result = rectangle_fit(rect, sections[key])
            result.update(room_id=room['room_id'], level_id=room['level_id'], room_name=room['name'],
                          test_plane=label, z_m=z, source_clear_height_m=room['clear_height_m'],
                          perimeter_allowance_m=allowance, residual_margin_m=result['perimeter_margin_m'] - allowance,
                          allowance_pass=bool(result['contained'] and result['perimeter_margin_m'] + EPS >= allowance))
            fits.append(result)
    failing = sorted({x['room_id'] for x in fits if not x['allowance_pass']})
    report = {'asset_id': spec['asset_id'], 'candidate': spec['revision'], 'status': 'INDEPENDENT GEOMETRY AUDIT; no design, shell, placement or engine approval',
              'method': 'Decode GLB position/index accessors; independent OBJ parser and coordinate/index comparison. Slice actual curtainwall triangles at each source room bottom and proposed clear-height top; stitch perimeter; test unchanged source rectangles against polygon including recess/concavity and shortest segment distances.',
              'coordinate_conversion': 'glTF (X,Y,Z) -> source (X,-Z,Y), verified by OBJ parity',
              'tolerances': {'target_dimension_m': 0.01, 'section_snap_m': EPS, 'obj_glb_coordinate_m': 2e-5, 'zero_area_threshold_m2': 1e-12},
              'input_hashes': {'MODEL_SPEC.json': sha(specpath), glbpath.name: sha(glbpath), objpath.name: sha(objpath), str(LAYOUT.relative_to(REPO)): sha(LAYOUT), 'audit_candidate.py': sha(Path(__file__))},
              'source_hash_checks': references, 'spec_targets_equal_original_json': targets_equal,
              'dimension_checks': checks, 'mesh_integrity': integrity,
              'source_bbox_min_m': allv.min(axis=0).tolist(), 'source_bbox_max_m': allv.max(axis=0).tolist(),
              'section_polygons_source_xy_m': {k: v.tolist() for k, v in sections.items()},
              'fit_tests': fits,
              'summary': {'objects': len(glb), 'triangles': sum(len(m['f']) for m in glb.values()), 'dimension_checks_pass': all(c['pass'] for c in checks),
                          'mesh_integrity_pass': all(x['pass'] for x in integrity), 'source_hashes_pass': all(x['pass'] for x in references) and targets_equal,
                          'room_count': len(fits) // 2, 'plane_tests': len(fits), 'allowance_failing_room_ids': failing,
                          'minimum_skin_margin_m': min(x['perimeter_margin_m'] for x in fits), 'minimum_residual_after_allowance_m': min(x['residual_margin_m'] for x in fits)},
              'limitations': ['Exterior skin containment only; no ribs/structure, core, furniture, player/camera, doors, lift or stair clearance certification.',
                              'Bottom/top sections do not prove interior clearance at every intervening height; all room coordinates and clear heights remain source proposals.',
                              'The 1.2 m perimeter allowance is a builder proposal, not a measured wall assembly or approved tolerance.',
                              'Holding the 68 x 54 m envelope to +135 m is a new C01 proposal; passing these tests cannot approve its visual match to the master.',
                              'Finite/index/area checks do not establish watertightness, UV quality, collision, navigation, performance, constructability or engine acceptance.',
                              'Source hashes prove byte provenance, not source design approval or absence of visual contradictions.',
                              'No render comparison or perspective calibration is performed by this script.'],
              'approval': None}
    (MODEL / 'FIT_REVIEW.json').write_text(json.dumps(report, indent=2) + '\n')
    with (MODEL / 'FIT_REVIEW.csv').open('w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=list(fits[0]))
        writer.writeheader()
        writer.writerows(fits)
    print(json.dumps(report['summary'], indent=2))
    print('Mesh failures:', [x['object'] for x in integrity if not x['pass']])


if __name__ == '__main__':
    main()
