"""Import only the isolated R06 TEST-ONLY meshes into a new Blender collection.

Dry-run outside Blender:
  python IMPORT_BLENDER.py --validate-only --package .
In Blender's Python console or background invocation, run with --package PATH.
No existing objects, scene units, cameras, engine configuration or D2 assets are
modified. JSON authoring coordinates are metres, X east, Y north, Z up.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
from pathlib import Path
import sys


def read_import_data(package):
    package = Path(package).resolve()
    raw = (package / "GEOMETRY_HANDOFF.json").read_bytes()
    manifest = json.loads((package / "ARTIFACT_MANIFEST.json").read_text())
    record = next(item for item in manifest["artifacts"] if item["path"] == "GEOMETRY_HANDOFF.json")
    if hashlib.sha256(raw).hexdigest() != record["sha256"]:
        raise ValueError("handoff checksum differs from the package manifest")
    data = json.loads(raw)
    if data["package_id"] != "SW-GEOMETRY-HANDOFF-R06" or data["schema_version"] != "1.0.0" or data["status"] != "TEST_ONLY_REVIEW_HANDOFF":
        raise ValueError("unsupported or non-test package")
    for gate in ("approved_for_construction", "accepted_world_integration", "actual_engine_import_verified"):
        if data["acceptance"].get(gate) is not False:
            raise ValueError("unexpected acceptance state")
    if data["coordinate_frames"]["SW-R06-SPECIMEN-LOCAL-M"]["units"] != "metres":
        raise ValueError("authoring units must be metres")
    features = {item["id"]: item for item in data["features"]}
    meshes = data["meshes"]
    names = set()
    for item in meshes:
        if item["id"] in names or item["classification"] != "test_only":
            raise ValueError("duplicate or non-test mesh")
        names.add(item["id"])
        feature = features[item["feature_id"]]
        if feature["frame_id"] != "SW-R06-SPECIMEN-LOCAL-M" or feature["classification"] != "test_only":
            raise ValueError("mesh is not in the isolated test authoring frame")
        if not item["vertices_m"] or not item["triangles"]:
            raise ValueError("empty mesh")
        for vertex in item["vertices_m"]:
            if len(vertex) != 3 or not all(type(v) in (int, float) and math.isfinite(v) for v in vertex):
                raise ValueError("invalid vertex")
        for triangle in item["triangles"]:
            if len(triangle) != 3 or not all(type(i) is int and 0 <= i < len(item["vertices_m"]) for i in triangle):
                raise ValueError("invalid triangle")
    return data


def import_collection(data):
    import bpy  # Imported only after the complete package dry-run succeeds.
    units=bpy.context.scene.unit_settings
    if not math.isfinite(units.scale_length) or abs(units.scale_length-1)>1e-9:
        raise ValueError("Scene scale_length must be 1 metre per Blender unit before any import. Use a fresh isolated 1m scene; existing scene settings are not changed.")
    name = "TEST_ONLY_SW_R06_DO_NOT_MERGE"
    object_names = ["SW_R06_" + item["id"] for item in data["meshes"]]
    control_names = ["SW_R06_AXIS_" + item["id"] for item in data["axis_controls"]]
    if bpy.data.collections.get(name) or any(bpy.data.objects.get(item) for item in object_names+control_names):
        raise ValueError("R06 test collection/object already exists; preserve it or remove it intentionally before reimport")
    collection = None
    created_objects, created_meshes, created_materials = [], [], []
    try:
        collection = bpy.data.collections.new(name)
        collection["classification"] = "test_only"
        collection["source_package"] = data["package_id"]
        collection["units"] = "metres; interpret coordinates directly; scene settings untouched"
        collection["scene_scale_length"] = units.scale_length
        collection["scene_unit_system"] = units.system
        collection["scene_length_unit"] = units.length_unit
        collection["world_integration"] = "UNRESOLVED; do not merge with the authoritative world"
        colors = {"road": (0.20, 0.25, 0.30, 1), "land": (0.48, 0.62, 0.49, 1),
                  "pedestrian": (0.89, 0.72, 0.40, 1)}
        materials = {}
        for key, color in colors.items():
            material = bpy.data.materials.new("SW_R06_TEST_" + key)
            created_materials.append(material)
            material.diffuse_color = color
            materials[key] = material
        for item, object_name in zip(data["meshes"], object_names):
            mesh = bpy.data.meshes.new(object_name + "_DATA")
            created_meshes.append(mesh)
            mesh.from_pydata(item["vertices_m"], [], item["triangles"])
            mesh.update()
            obj = bpy.data.objects.new(object_name, mesh)
            created_objects.append(obj)
            obj["classification"] = "test_only"
            obj["feature_id"] = item["feature_id"]
            obj["authoring_frame"] = "SW-R06-SPECIMEN-LOCAL-M"
            obj["source_units"] = "metres"
            obj["approved_for_construction"] = False
            mesh.materials.append(materials.get(item["material"], materials["road"]))
            collection.objects.link(obj)
        for control,object_name in zip(data["axis_controls"],control_names):
            obj=bpy.data.objects.new(object_name,None)
            created_objects.append(obj)
            obj.location=control["authoring_m"]
            obj.empty_display_type="PLAIN_AXES"
            obj.empty_display_size=1
            obj["classification"]="test_only_nonphysical_axis_control"
            obj["authoring_frame"]="SW-R06-SPECIMEN-LOCAL-M"
            obj["expected_interface_cm_before_R_T"]=control["expected_interface_cm_before_R_T"]
            collection.objects.link(obj)
        # Attach only when every object has been created successfully.
        bpy.context.scene.collection.children.link(collection)
        return name
    except Exception:
        for obj in created_objects:
            bpy.data.objects.remove(obj, do_unlink=True)
        for mesh in created_meshes:
            if mesh.users == 0:
                bpy.data.meshes.remove(mesh)
        if collection is not None:
            bpy.data.collections.remove(collection)
        for material in created_materials:
            if material.users == 0:
                bpy.data.materials.remove(material)
        raise


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--package", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--validate-only", action="store_true")
    args = parser.parse_args(argv)
    data = read_import_data(args.package)
    count = len(data["meshes"])
    if args.validate_only:
        print(f"PASS: {count} test-only meshes preflighted; Blender scene not accessed")
    else:
        name = import_collection(data)
        print(f"Created {name} with {count} meshes. TEST ONLY; no world transform or engine acceptance.")
    return 0


if __name__ == "__main__":
    cli = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
    raise SystemExit(main(cli))
