#!/usr/bin/env python3
"""All-room fit coverage for a Crown Landmark exterior candidate.

Measures the unchanged INT R02 room rectangles (all 81) against the actual
exported GLB of a candidate. Writes a report, a per-room CSV, plan sections for
every defined level and two vertical sections. It never edits a candidate, the
interior layout or any source reference. Needs Python 3, NumPy and matplotlib.

    python fit_coverage.py C01        # reads ../SHELL-C01/MODEL/*.glb
    python fit_coverage.py C02

Evidence labels used throughout:
  measured     = a slice, bound, distance or sampled-vertex test on the actual mesh
  proposed     = a value the candidate itself proposes (slab thickness, allowance)
  interpreted  = a reading of which enclosure governs; needs a human decision
"""
from pathlib import Path
import csv
import hashlib
import importlib.util
import json
import sys
import numpy as np

HERE = Path(__file__).resolve().parent
RELEASE = HERE.parent
REPO = next(p for p in HERE.parents if (p / 'AGENTS.md').exists())
LAYOUT = REPO / 'production/assets/buildings/PI-BLD-0001-V01/INT/R02/06_Handoff/EditableLayout/INTERIOR_LAYOUT.json'
ALLOWANCE = 1.2   # the candidates' proposed perimeter allowance (not an approved tolerance)


def load_audit_module():
    path = RELEASE / 'SHELL-C01' / 'audit_candidate.py'
    spec = importlib.util.spec_from_file_location('audit_candidate', path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


A = load_audit_module()
EPS = A.EPS


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


def rect_of(room):
    x, y, w, d = (room[k] for k in ['x_m', 'y_m', 'width_m', 'depth_m'])
    return np.asarray([[x, y], [x + w, y], [x + w, y + d], [x, y + d]], float)


def slice_loop(mesh, z):
    return A.section(mesh, z)


def poly_bounds(poly):
    return poly[:, 0].min(), poly[:, 0].max(), poly[:, 1].min(), poly[:, 1].max()


def part_bounds(mesh):
    v = mesh['v']
    return v.min(axis=0), v.max(axis=0)


def box_union_polygon(glb, names):
    lo = np.array([1e9, 1e9, 1e9]); hi = -lo
    for n in names:
        a, b = part_bounds(glb[n]); lo = np.minimum(lo, a); hi = np.maximum(hi, b)
    return np.array([[lo[0], lo[1]], [hi[0], lo[1]], [hi[0], hi[1]], [lo[0], hi[1]]]), lo[2], hi[2]


def enclosure(glb, spec):
    """Per podium tier: wall polygon, deck cap outline, soffit height. All read from the mesh."""
    decks = spec['targets']['podium_decks']
    tiers, base = {}, 0.0
    for i, deck in enumerate(decks, 1):
        z = float(deck['z_m'])
        deck_name = next(n for n in glb if n.startswith(f'Deck_{i}_top_'))
        deck_mesh = glb[deck_name]
        outline = slice_loop(deck_mesh, z - 0.001)            # outer lip of the slab
        if f'Podium_wall_{i}' in glb:                          # C02+: explicit enclosure part
            wall_mesh = glb[f'Podium_wall_{i}']
            wall = slice_loop(wall_mesh, (base + z) / 2)
            wall_part = f'Podium_wall_{i}'
        elif i == 1 and 'Podium_rear_glazing' in glb:        # C01 tier 1: four separate glazing boxes
            names = [n for n in glb if n.startswith(('Arrival_glazing_', 'Podium_side_glazing_', 'Podium_rear_glazing'))]
            wall, _, _ = box_union_polygon(glb, names)
            wall_part = 'Arrival_glazing_* + Podium_side_glazing_* + Podium_rear_glazing (bounding rectangle)'
        else:
            wall = slice_loop(glb[f'Podium_glazing_{i}'], (base + z) / 2)
            wall_part = f'Podium_glazing_{i}'
        # soffit over the enclosed floor = lowest deck vertex that lies inside the wall polygon
        inside = [v for v in deck_mesh['v'] if A.inside(v[:2], wall)]
        soffit = float(min(v[2] for v in inside)) if inside else float(deck_mesh['v'][:, 2].min())
        tiers[i] = {'base_z': base, 'deck_z': z, 'deck_part': deck_name, 'wall': wall, 'wall_part': wall_part,
                    'deck_outline': outline, 'soffit_z': soffit,
                    'deck_nominal_m': [deck['width_m'], deck['depth_m']]}
        base = z
    return tiers


def tier_for(z, tiers):
    for i, t in tiers.items():
        if t['base_z'] - EPS <= z < t['deck_z'] - EPS:
            return i
    return None


def triangle_samples(mesh, n=4):
    """Barycentric lattice on every triangle: denser than the mesh so a thin rib cannot hide between vertices."""
    tri = mesh['v'][mesh['f']]
    pts = []
    for i in range(n + 1):
        for j in range(n + 1 - i):
            a, b = i / n, j / n
            pts.append(tri[:, 0] * (1 - a - b) + tri[:, 1] * a + tri[:, 2] * b)
    return np.concatenate(pts)


def rib_hits(glb, rect, z0, z1):
    x0, x1, y0, y1 = rect[:, 0].min(), rect[:, 0].max(), rect[:, 1].min(), rect[:, 1].max()
    hits = {}
    for name, mesh in glb.items():
        if not name.startswith('Rib_'):
            continue
        p = triangle_samples(mesh)
        m = (p[:, 0] > x0) & (p[:, 0] < x1) & (p[:, 1] > y0) & (p[:, 1] < y1) & (p[:, 2] > z0) & (p[:, 2] < z1)
        if m.any():
            hits[name] = int(m.sum())
    return hits


def classify(contained, margin, deck_ok, tower=False):
    if contained and margin + EPS >= ALLOWANCE:
        return 'FITS'
    if contained:
        return 'INSIDE_BELOW_ALLOWANCE'
    if tower:
        return 'OUTSIDE_SKIN'
    return 'OUTSIDE_WALL_INSIDE_DECK' if deck_ok else 'OUTSIDE_WALL_AND_DECK'


def run(label):
    release = RELEASE / f'SHELL-{label}'
    model = release / 'MODEL'
    prefix = f'PI-BLD-0001-V01_CrownLandmark_SHELL_{label}'
    spec = json.loads((release / 'MODEL_SPEC.json').read_text())
    layout = json.loads(LAYOUT.read_text())
    glb = A.read_glb(model / (prefix + '.glb'))
    tiers = enclosure(glb, spec)
    skin_name = 'Tower_curtainwall_skin'
    skin_cache = {}
    rows = []
    for room in layout['rooms']:
        rect = rect_of(room)
        z0 = float(room['z_m']); z1 = z0 + float(room['clear_height_m'])
        row = {'room_id': room['room_id'], 'level_id': room['level_id'], 'room_name': room['name'], 'z_bottom_m': z0,
               'z_top_m': z1, 'rect_x_m': [float(rect[0, 0]), float(rect[1, 0])], 'rect_y_m': [float(rect[0, 1]), float(rect[2, 1])]}
        if room['level_id'] in ('L25', 'L26'):
            fits = []
            for z in (z0, z1):
                key = round(z, 6)
                if key not in skin_cache:
                    skin_cache[key] = slice_loop(glb[skin_name], z)
                fits.append(A.rectangle_fit(rect, skin_cache[key]))
            margin = min(f['perimeter_margin_m'] for f in fits)
            contained = all(f['contained'] for f in fits)
            row.update(governing='Tower curtainwall skin (sections at room bottom and clear-height top)',
                       governing_evidence='measured', wall_margin_m=margin, wall_contained=contained,
                       deck_outline_margin_m=None, ceiling_clearance_m=None,
                       residual_after_allowance_m=margin - ALLOWANCE, status=classify(contained, margin, True, tower=True))
        else:
            ti = tier_for(z0, tiers)
            t = tiers[ti]
            fw = A.rectangle_fit(rect, t['wall'])
            fd = A.rectangle_fit(rect, t['deck_outline'])
            above = [o for o in layout['rooms'] if o['level_id'] != room['level_id'] and float(o['z_m']) >= z1 - EPS
                     and float(o['z_m']) < t['deck_z'] - EPS and not (o['x_m'] >= rect[1, 0] or o['x_m'] + o['width_m'] <= rect[0, 0]
                     or o['y_m'] >= rect[2, 1] or o['y_m'] + o['depth_m'] <= rect[0, 1])]
            # headroom is only meaningful where no defined room sits above this one inside the same tier
            ceiling = None if above else t['soffit_z'] - z1
            row.update(governing=f"Tier {ti}: wall = {t['wall_part']}; roof = {t['deck_part']} (+{t['deck_z']:g} m)",
                       governing_evidence='measured geometry; which enclosure governs is interpreted',
                       wall_margin_m=fw['perimeter_margin_m'], wall_contained=fw['contained'],
                       deck_outline_margin_m=fd['perimeter_margin_m'] if fd['contained'] else fd['perimeter_margin_m'],
                       deck_outline_contained=fd['contained'],
                       ceiling_clearance_m=ceiling, residual_after_allowance_m=fw['perimeter_margin_m'] - ALLOWANCE,
                       status=classify(fw['contained'], fw['perimeter_margin_m'], fd['contained']))
        hits = rib_hits(glb, rect, z0, z1)
        row['rib_intrusions'] = hits
        rows.append(row)
    levels = {}
    for r in rows:
        levels.setdefault(r['level_id'], []).append(r)
    summary = {
        'rooms_in_layout': len(rows), 'rooms_measured': len(rows),
        'by_status': {s: sum(r['status'] == s for r in rows) for s in sorted({r['status'] for r in rows})},
        'by_level': {k: {s: sum(r['status'] == s for r in v) for s in sorted({r['status'] for r in v})} for k, v in levels.items()},
        'rooms_with_rib_intrusion': sorted(r['room_id'] for r in rows if r['rib_intrusions']),
        'ceiling_conflicts': sorted(r['room_id'] for r in rows if r.get('ceiling_clearance_m') is not None and r['ceiling_clearance_m'] < -EPS),
        'ceiling_note': 'ceiling_clearance_m = lowest deck vertex over the enclosed floor minus the room clear-height top; reported only where no defined room sits above in the same tier. The 0.9 m slab thickness is a candidate proposal.',
        'levels_with_layout': sorted(levels), 'levels_without_layout_count': 45 - len(levels),
        'floors_total': spec['targets']['floor_count'],
    }
    return spec, glb, tiers, skin_cache, rows, summary, model, prefix


def draw_sections(label, spec, glb, tiers, rows, outdir):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from matplotlib.patches import Polygon, Rectangle
    colors = {'FITS': ('#3b9c6e', '#d5f0e1'), 'INSIDE_BELOW_ALLOWANCE': ('#d98a1f', '#fbe9c9'),
              'OUTSIDE_WALL_INSIDE_DECK': ('#c0392b', '#f6d0cb'), 'OUTSIDE_WALL_AND_DECK': ('#7b1fa2', '#e5cdee'), 'OUTSIDE_SKIN': ('#c0392b', '#f6d0cb')}
    plans = {'L00': 0.0, 'L01': 6.0, 'L02': 12.0, 'L03': 18.0, 'L25': 126.0, 'L26': 130.5}
    skin = glb['Tower_curtainwall_skin']
    names = sorted(plans)
    fig, axes = plt.subplots(2, 3, figsize=(20, 12.4))
    for ax, lv in zip(axes.flat, names):
        z = plans[lv]
        if lv in ('L25', 'L26'):
            for zz, ls in ((z, '-'), (z + 3.6, '--')):
                poly = slice_loop(skin, zz)
                ax.add_patch(Polygon(poly, closed=True, fill=False, ec='#1d4e89', lw=2 if ls == '-' else 1.2, ls=ls))
            ax.set_xlim(-45, 45); ax.set_ylim(-36, 36)
            note = f'Tower skin sections at +{z:g} m (solid) and +{z + 3.6:g} m (dashed). Measured on the actual GLB.'
        else:
            ti = tier_for(z, tiers); t = tiers[ti]
            ax.add_patch(Polygon(t['deck_outline'], closed=True, fill=False, ec='#777', lw=1.2, ls=':'))
            ax.add_patch(Polygon(t['wall'], closed=True, fill=False, ec='#1d4e89', lw=2.2))
            b = t['deck_outline']
            ax.set_xlim(b[:, 0].min() - 6, b[:, 0].max() + 6); ax.set_ylim(b[:, 1].min() - 6, b[:, 1].max() + 6)
            note = (f"Tier {ti}: blue = wall line ({t['wall_part'].split(' ')[0]}), dotted = roof deck outline "
                    f"(+{t['deck_z']:g} m, {t['deck_nominal_m'][0]:g}x{t['deck_nominal_m'][1]:g}). Measured.")
        for r in rows:
            if r['level_id'] != lv:
                continue
            ec, fc = colors[r['status']]
            x0, x1 = r['rect_x_m']; y0, y1 = r['rect_y_m']
            ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc=fc, ec=ec, lw=1.4, alpha=.9))
            if (x1 - x0) * (y1 - y0) > 60 or r['status'] != 'FITS':
                ax.text((x0 + x1) / 2, (y0 + y1) / 2, r['room_id'].split('-')[1], ha='center', va='center', fontsize=6.5, color='#222')
        ax.set_aspect('equal'); ax.set_title(f'{lv}  z={z:g} m   ({sum(1 for r in rows if r["level_id"] == lv)} rooms)', fontsize=12)
        ax.set_xlabel('x (m, local right)\n' + note, fontsize=8); ax.set_ylabel('y (m, rear +; front is -y)', fontsize=8)
        ax.grid(alpha=.2)
    fig.suptitle(f'Crown Landmark {label}: plan sections for every level that has a room layout (all 81 rooms)', fontsize=15, y=.995)
    keys = ['FITS', 'INSIDE_BELOW_ALLOWANCE', 'OUTSIDE_WALL_INSIDE_DECK', 'OUTSIDE_WALL_AND_DECK', 'OUTSIDE_SKIN']
    legend = [Rectangle((0, 0), 1, 1, fc=colors[k][1], ec=colors[k][0]) for k in keys]
    fig.legend(legend, ['Fits with 1.2 m proposed allowance', 'Inside wall or skin, below allowance', 'Outside wall line, inside deck outline', 'Outside wall line and deck outline', 'Outside tower skin'], loc='lower center', ncol=5, fontsize=10)
    fig.tight_layout(rect=(0, .04, 1, .97))
    fig.savefig(outdir / f'{label}_plan_sections_all_levels.png', dpi=110)
    fig.savefig(outdir / f'{label}_plan_sections_all_levels.svg')
    plt.close(fig)

    # vertical sections through x = 0 (atrium and portal) and x = -17 (west gallery)
    def span_at(poly, x):
        ys = []
        for a, b in zip(poly, np.roll(poly, -1, axis=0)):
            if (a[0] - x) * (b[0] - x) < 0:
                ys.append(a[1] + (x - a[0]) * (b[1] - a[1]) / (b[0] - a[0]))
        return (min(ys), max(ys)) if len(ys) >= 2 else None
    fig, axes = plt.subplots(1, 2, figsize=(20, 12))
    for ax, x in zip(axes, (0.0, -17.0)):
        for i, t in tiers.items():
            sp = span_at(t['deck_outline'], x); wp = span_at(t['wall'], x)
            if sp:
                ax.add_patch(Rectangle((sp[0], t['soffit_z']), sp[1] - sp[0], t['deck_z'] - t['soffit_z'], fc='#cfc6b8', ec='#555', lw=1))
                ax.text(sp[1] + .8, t['deck_z'], f'Deck {i} +{t["deck_z"]:g}', fontsize=7)
            if wp:
                for yv in wp:
                    ax.plot([yv, yv], [t['base_z'], t['deck_z'] - (t['deck_z'] - t['soffit_z'])], color='#1d4e89', lw=2.4)
        for zz in np.linspace(54, 240 if False else 216, 40):
            sp = span_at(slice_loop(skin, float(zz)), x)
            if sp:
                ax.plot([sp[0], sp[0]], [zz, min(zz + 4.6, 216)], color='#1d4e89', lw=1.2)
                ax.plot([sp[1], sp[1]], [zz, min(zz + 4.6, 216)], color='#1d4e89', lw=1.2)
        for r in rows:
            x0, x1 = r['rect_x_m']
            if not (x0 <= x <= x1):
                continue
            y0, y1 = r['rect_y_m']
            ec, fc = colors[r['status']]
            ax.add_patch(Rectangle((y0, r['z_bottom_m']), y1 - y0, r['z_top_m'] - r['z_bottom_m'], fc=fc, ec=ec, lw=.9, alpha=.85))
        ax.set_xlim(-62, 62); ax.set_ylim(-4, 240); ax.set_aspect('equal')
        ax.set_title(f'Vertical section at x = {x:g} m (looking along x; front is at left, -y)', fontsize=11)
        ax.set_xlabel('y (m)'); ax.set_ylabel('height above finished ground (m)'); ax.grid(alpha=.2)
    fig.suptitle(f'Crown Landmark {label}: vertical sections (measured slabs, wall lines, tower skin and the rooms that cross each plane)', fontsize=14)
    fig.tight_layout(rect=(0, 0, 1, .97))
    fig.savefig(outdir / f'{label}_vertical_sections.png', dpi=100)
    fig.savefig(outdir / f'{label}_vertical_sections.svg')
    plt.close(fig)

    # podium close-up, longitudinal at x = 0 and x = -17, heights 0-60 m so L00-L03 are legible
    fig, axes = plt.subplots(1, 2, figsize=(20, 8.5))
    for ax, x in zip(axes, (0.0, -17.0)):
        for i, t in tiers.items():
            sp = span_at(t['deck_outline'], x); wp = span_at(t['wall'], x)
            if sp:
                ax.add_patch(Rectangle((sp[0], t['soffit_z']), sp[1] - sp[0], t['deck_z'] - t['soffit_z'], fc='#cfc6b8', ec='#555', lw=1))
            if wp:
                for yv in wp:
                    ax.plot([yv, yv], [t['base_z'], t['soffit_z']], color='#1d4e89', lw=2.6)
        for r in rows:
            x0, x1 = r['rect_x_m']
            if r['level_id'] in plans and plans[r['level_id']] < 30 and x0 <= x <= x1:
                y0, y1 = r['rect_y_m']; ec, fc = colors[r['status']]
                ax.add_patch(Rectangle((y0, r['z_bottom_m']), y1 - y0, r['z_top_m'] - r['z_bottom_m'], fc=fc, ec=ec, lw=1.1, alpha=.9))
                ax.text((y0 + y1) / 2, (r['z_bottom_m'] + r['z_top_m']) / 2, r['room_id'].split('-')[1], ha='center', va='center', fontsize=7)
        ax.set_xlim(-62, 40); ax.set_ylim(-2, 40); ax.set_aspect('equal'); ax.grid(alpha=.2)
        ax.set_title(f'Podium close-up, vertical section at x = {x:g} m', fontsize=11)
        ax.set_xlabel('y (m); front is -y at left'); ax.set_ylabel('height (m)')
    fig.tight_layout()
    fig.savefig(outdir / f'{label}_podium_vertical_closeup.png', dpi=100)
    fig.savefig(outdir / f'{label}_podium_vertical_closeup.svg')
    plt.close(fig)


def main():
    label = sys.argv[1] if len(sys.argv) > 1 else 'C01'
    outdir = HERE / label
    outdir.mkdir(exist_ok=True)
    spec, glb, tiers, skin_cache, rows, summary, model, prefix = run(label)
    enclosure_report = {str(i): {'base_z_m': t['base_z'], 'roof_deck_z_m': t['deck_z'], 'deck_part': t['deck_part'],
                                 'wall_part': t['wall_part'], 'wall_bounds_xy_m': [float(v) for v in poly_bounds(t['wall'])],
                                 'wall_vertices': len(t['wall']),
                                 'deck_outline_bounds_xy_m': [float(v) for v in poly_bounds(t['deck_outline'])],
                                 'soffit_over_enclosed_floor_m': t['soffit_z'],
                                 'nominal_deck_wxd_m': t['deck_nominal_m']} for i, t in tiers.items()}
    report = {
        'asset_id': spec['asset_id'], 'candidate': label,
        'status': 'ALL-ROOM FIT COVERAGE; measured containment only. No design, shell, placement or engine approval.',
        'model': {'glb': prefix + '.glb', 'glb_sha256': sha(model / (prefix + '.glb')),
                  'layout_sha256': sha(LAYOUT), 'script_sha256': sha(__file__)},
        'method': ('Every one of the 81 unchanged INT R02 room rectangles is tested at its floor and clear-height top. '
                   'L25/L26: sections of the actual tower curtainwall skin (same method as the C01 audit). '
                   'L00-L03: the wall line and roof deck outline of the podium tier that contains the level are read from the '
                   'actual GLB parts; the room must lie inside the wall line with at least the proposed 1.2 m allowance. '
                   'A room outside the wall line but inside the roof deck outline projects into the arcade zone. '
                   'Ceiling clearance is the lowest deck vertex over the enclosed floor minus the room clear-height top. '
                   'Ribs are tested by dense triangle sampling against each room prism.'),
        'evidence_labels': {'measured': 'distance, slice or sampled-vertex result on the actual mesh',
                            'proposed': '1.2 m allowance and slab thickness are candidate proposals, not approved tolerances',
                            'interpreted': 'which enclosure governs each level is a reading of R06 targets and the candidate geometry; it needs a recorded decision'},
        'enclosures_read_from_model': enclosure_report,
        'summary': summary,
        'not_covered': ['Levels L04-L24 and L27-L44 have no room layout in INT R02 (39 of 45 floors).',
                        'Doors, stairs, lifts, furniture, player or camera envelopes and furnished clearances.',
                        'Heights between each room\'s floor and clear-height top.',
                        'Watertight construction, collision, LODs, UVs and any engine behaviour.'],
        'rooms': rows,
        'approval': None,
    }
    (outdir / f'{label}_FIT_COVERAGE.json').write_text(json.dumps(report, indent=2, default=lambda o: o.tolist() if hasattr(o, 'tolist') else str(o)) + '\n')
    fields = ['room_id', 'level_id', 'room_name', 'z_bottom_m', 'z_top_m', 'status', 'wall_margin_m', 'residual_after_allowance_m',
              'deck_outline_margin_m', 'ceiling_clearance_m', 'rib_intrusions', 'governing', 'governing_evidence']
    with (outdir / f'{label}_FIT_COVERAGE.csv').open('w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction='ignore'); w.writeheader()
        for r in rows:
            w.writerow({**r, 'rib_intrusions': json.dumps(r['rib_intrusions'])})
    draw_sections(label, spec, glb, tiers, rows, outdir)
    print(json.dumps(summary, indent=2))


if __name__ == '__main__':
    main()
