"""INT R02 diagnostic overlay for the Crown Landmark (PI-BLD-0001-V01) build.

READ-ONLY visualisation. Adds collection INT_R02_Overlay with one wireframe box per INT R02 room so the room
blocks can be seen against the exterior shell. Nothing is moved, resized or edited; the layout JSON is only read.
This is NOT one of the five build modules: assemble.py must never import it.

Run inside Blender (bpy), on an assembled model:
    blender --background --factory-startup <model.blend> --python overlay_int_r02.py -- [options]
or from the Scripting editor (Run Script; options then come from the environment only).

Options (after `--`)                      env fallback
    --layout <layout.json>                INT_R02_LAYOUT      (default C:/q2/layout.json)
    --status-csv <fit.csv>                INT_R02_STATUS_CSV  (csv columns: room_id,status; optional, missing = ignored)
When neither --status-csv nor the env var is given, the default CSV
    <CrownLandmark>/out/fit_C03_r4/fit_C03_r4.csv
is used if it exists.

Frame: metres, Z up, front -Y, origin = tower centre at ground. Box = [x, x+width] x [y, y+depth] x [z, z+clear_height],
(x_m, y_m) is the MIN corner. Re-running replaces the overlay (idempotent).

Colours: level group L00-L03 cyan, L25 violet, L26 pink. With a status CSV: FITS green,
INSIDE_BELOW_ALLOWANCE amber, OUTSIDE_SKIN / OUTSIDE_WALL red, anything else grey.
Overlay collection and objects are hide_render + hide_select, transforms locked.
"""
import csv
import hashlib
import json
import os
import sys

import bpy

COLLECTION = "INT_R02_Overlay"
MATERIAL = "INTR02_overlay_mat"
DEFAULT_LAYOUT = r"C:\q2\layout.json"
HERE = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
DEFAULT_STATUS_CSV = os.path.normpath(os.path.join(HERE, "..", "out", "fit_C03_r4", "fit_C03_r4.csv"))

GROUP_COLOURS = {  # level group -> RGBA
    "L00-L03": (0.10, 0.75, 1.00, 1.0),
    "L25": (0.65, 0.30, 1.00, 1.0),
    "L26": (1.00, 0.35, 0.80, 1.0),
}
STATUS_COLOURS = {
    "FITS": (0.10, 0.85, 0.20, 1.0),
    "INSIDE_BELOW_ALLOWANCE": (1.00, 0.70, 0.05, 1.0),
    "OUTSIDE_SKIN": (1.00, 0.10, 0.10, 1.0),
    "OUTSIDE_WALL": (1.00, 0.10, 0.10, 1.0),
}
UNKNOWN_COLOUR = (0.6, 0.6, 0.6, 1.0)


def _argv():
    return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []


def _arg(name, env=None, default=None):
    a = _argv()
    if name in a and a.index(name) + 1 < len(a):
        return a[a.index(name) + 1]
    if env and os.environ.get(env):
        return os.environ[env]
    return default


def load_layout(path):
    """Return (rooms, sha256_hex_of_file). Raises on a missing/invalid layout."""
    with open(path, "rb") as f:
        raw = f.read()
    data = json.loads(raw.decode("utf-8-sig"))
    return data["rooms"], hashlib.sha256(raw).hexdigest()


def load_status(path):
    """room_id -> status from a CSV with columns room_id,status. Missing/invalid file -> {} (with a message)."""
    if not path:
        return {}
    if not os.path.isfile(path):
        print(f"[INTR02] status CSV not found, using level colours: {path}")
        return {}
    try:
        with open(path, newline="", encoding="utf-8-sig") as f:
            rd = csv.DictReader(f)
            if not rd.fieldnames or "room_id" not in rd.fieldnames or "status" not in rd.fieldnames:
                print(f"[INTR02] status CSV lacks room_id,status columns, ignored: {path}")
                return {}
            return {(r["room_id"] or "").strip(): (r["status"] or "").strip().upper() for r in rd}
    except Exception as e:  # never let a bad CSV break the overlay
        print(f"[INTR02] status CSV unreadable ({e!r}), ignored: {path}")
        return {}


def level_group(level_id):
    if level_id in ("L00", "L01", "L02", "L03"):
        return "L00-L03"
    return level_id if level_id in GROUP_COLOURS else None


def _material():
    mat = bpy.data.materials.get(MATERIAL) or bpy.data.materials.new(MATERIAL)
    mat.diffuse_color = (1.0, 1.0, 1.0, 0.15)  # viewport only; transparent, shared
    try:
        mat.surface_render_method = "BLENDED"
    except Exception:
        pass
    return mat


def _clear_existing():
    col = bpy.data.collections.get(COLLECTION)
    if col is None:
        return
    for ob in list(col.objects):
        me = ob.data
        bpy.data.objects.remove(ob, do_unlink=True)
        if me is not None and me.users == 0:
            bpy.data.meshes.remove(me)
    bpy.data.collections.remove(col)


def build_overlay(layout_path=None, status_csv=None):
    layout_path = layout_path or DEFAULT_LAYOUT
    rooms, sha = load_layout(layout_path)
    status = load_status(status_csv)
    _clear_existing()

    col = bpy.data.collections.new(COLLECTION)
    bpy.context.scene.collection.children.link(col)
    col["source_sha256"] = sha
    col["source_layout"] = os.path.abspath(layout_path)
    mat = _material()

    faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
    n = 0
    for r in rooms:
        rid, lvl = r["room_id"], r["level_id"]
        x, y, z = float(r["x_m"]), float(r["y_m"]), float(r["z_m"])
        w, d, h = float(r["width_m"]), float(r["depth_m"]), float(r["clear_height_m"])
        # local verts relative to the min corner; object location = min corner (world metres)
        verts = [(0, 0, 0), (w, 0, 0), (w, d, 0), (0, d, 0), (0, 0, h), (w, 0, h), (w, d, h), (0, d, h)]
        me = bpy.data.meshes.new(f"INTR02_{rid}")
        me.from_pydata(verts, [], faces)
        me.update()
        me.materials.append(mat)
        ob = bpy.data.objects.new(f"INTR02_{rid}", me)
        col.objects.link(ob)
        ob.location = (x, y, z)
        ob.display_type = "WIRE"
        ob.show_in_front = True
        ob.show_wire = True
        ob.visible_shadow = False
        ob["int_r02_room_id"] = rid
        ob["level_id"] = lvl
        ob["source_sha256"] = sha
        ob["room_name"] = r.get("name", "")
        if status:
            st = status.get(rid)
            ob["fit_status"] = st or "NO_STATUS"
            ob.color = STATUS_COLOURS.get(st, UNKNOWN_COLOUR)
        else:
            ob.color = GROUP_COLOURS.get(level_group(lvl), UNKNOWN_COLOUR)
        ob.lock_location = ob.lock_rotation = ob.lock_scale = (True, True, True)
        ob.hide_select = True
        ob.hide_render = True
        n += 1
    col.hide_render = True
    col.hide_select = True

    # make wire colours follow Object.color (display only, no effect on geometry)
    try:
        bpy.context.scene.display.shading.wireframe_color_type = "OBJECT"
    except Exception:
        pass
    for win in getattr(bpy.context, "window_manager", None).windows if getattr(bpy.context, "window_manager", None) else []:
        for area in win.screen.areas:
            if area.type == "VIEW_3D":
                try:
                    area.spaces.active.shading.wireframe_color_type = "OBJECT"
                except Exception:
                    pass
    print(f"[INTR02] overlay built: {n} rooms, status_rows={len(status)}, sha256={sha[:12]}")
    return col


def verify(layout_path=None, tol=1e-6):
    """Compare every overlay object's world bounds (location + mesh extents, float64) with the layout. Returns dict."""
    rooms, sha = load_layout(layout_path or DEFAULT_LAYOUT)
    col = bpy.data.collections[COLLECTION]
    by_id = {ob["int_r02_room_id"]: ob for ob in col.objects}
    bad, worst = [], 0.0
    for r in rooms:
        ob = by_id.get(r["room_id"])
        if ob is None:
            bad.append((r["room_id"], "missing"))
            continue
        # double-precision check of the stored data: location (min corner) + local vertex extents.
        # (matrix_world is float32; at z=130 m its rounding alone is ~1e-5 m, so it cannot be held to 1e-6.)
        vs = [tuple(v.co) for v in ob.data.vertices]
        loc = tuple(ob.location)
        lo = [loc[i] + min(p[i] for p in vs) for i in range(3)]
        hi = [loc[i] + max(p[i] for p in vs) for i in range(3)]
        want_lo = [r["x_m"], r["y_m"], r["z_m"]]
        want_hi = [r["x_m"] + r["width_m"], r["y_m"] + r["depth_m"], r["z_m"] + r["clear_height_m"]]
        err = max(abs(a - b) for a, b in zip(lo + hi, want_lo + want_hi))
        worst = max(worst, err)
        if err > tol:
            bad.append((r["room_id"], err))
    return {"objects": len(col.objects), "rooms": len(rooms), "matched": len(rooms) - len(bad),
            "max_err_m": worst, "mismatches": bad, "sha256": sha}


def main():
    layout = _arg("--layout", "INT_R02_LAYOUT", DEFAULT_LAYOUT)
    csv_path = _arg("--status-csv", "INT_R02_STATUS_CSV", None)
    if csv_path is None and os.path.isfile(DEFAULT_STATUS_CSV):
        csv_path = DEFAULT_STATUS_CSV
    build_overlay(layout, csv_path)


if not os.environ.get("INT_R02_NO_AUTORUN"):  # set INT_R02_NO_AUTORUN=1 to import the functions without building
    main()
