"""Portable isolated importer for the PROPOSED R07 regional foundation.

Default imports only proposed physical meshes and nonphysical unit controls.
Source-pixel data is never inserted into the metre scene. Historical native
comparison outlines are opt-in, separately named and explicitly nonphysical.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import sys
import tempfile
from region_io import load_region


PACKAGE_ID="SW-REGIONAL-FOUNDATION-R07"
COLLECTION="PROPOSED_SW_R07_DO_NOT_MERGE"


def preflight_save_path(path):
    if path is None:return None
    path=Path(path).expanduser().absolute()
    if path.exists() or path.is_symlink():raise ValueError("save-blend refuses an existing path; choose a new .blend filename")
    path=path.parent.resolve()/path.name
    if path.suffix.lower()!=".blend" or not path.parent.is_dir():raise ValueError("save-blend needs a new .blend filename in an existing directory")
    return path


def save_new_blend(path):
    """Save a copy, then atomically link to a new path without overwriting."""
    import bpy
    with tempfile.TemporaryDirectory(prefix=".sw-r07-save-",dir=path.parent) as temporary:
        staged=Path(temporary)/"candidate.blend"
        result=bpy.ops.wm.save_as_mainfile(filepath=str(staged),check_existing=False,copy=True)
        if "FINISHED" not in result or not staged.is_file() or staged.stat().st_size==0:raise ValueError("Blender did not produce a saved candidate copy")
        os.link(staged,path)  # Atomic no-clobber: an intervening existing path also fails.


def preflight(package,include_comparison=False):
    package=Path(package).resolve()
    raw=(package/"REGIONAL_GEOMETRY.json").read_bytes()
    manifest=json.loads((package/"ARTIFACT_MANIFEST.json").read_text())
    expected=next(item for item in manifest["artifacts"] if item["path"]=="REGIONAL_GEOMETRY.json")
    if hashlib.sha256(raw).hexdigest()!=expected["sha256"]:raise ValueError("canonical regional JSON checksum changed")
    data=load_region(package)
    if data.get("package_id")!=PACKAGE_ID or data.get("schema_version")!="1.1.0" or data.get("status")!="PROPOSED_REGIONAL_DESIGN_REVIEW":
        raise ValueError("unsupported candidate or package")
    gates=data["acceptance"]
    for field in ("approved_for_construction","accepted_world_integration","actual_engine_import_verified"):
        if gates.get(field) is not False:raise ValueError("unexpected approval claim")
    if gates.get("accepted_world_transform") is not None:raise ValueError("authoritative world placement must be unresolved")
    if data["frame"]["units"]!="metres" or data["frame"]["handedness"]!="right-handed":raise ValueError("wrong authoring units/handedness")
    features={item["id"]:item for item in data["features"]}
    names=set();physical=[]
    for mesh in data["meshes"]:
        if mesh["id"] in names:raise ValueError("duplicate mesh")
        names.add(mesh["id"])
        if mesh.get("physical_layer") is not True:continue
        feature=features[mesh["feature_id"]]
        if mesh["classification"]!="proposed_metric" or feature["classification"]!="proposed_metric" or feature.get("physical_layer") is not True:
            raise ValueError("physical mesh refers to source/comparison data")
        if not mesh["vertices_m"] or not mesh["triangles"]:raise ValueError("empty physical mesh")
        for vertex in mesh["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 physical vertex")
        for face in mesh["triangles"]:
            if len(face)!=3 or not all(type(v) is int and 0<=v<len(mesh["vertices_m"]) for v in face):raise ValueError("invalid face index")
        physical.append(mesh)
    if not physical:raise ValueError("no proposed physical region geometry")
    context=None
    if include_comparison:
        raw=(package/"SOURCE_CONTEXT.json").read_bytes()
        expected=next(item for item in manifest["artifacts"] if item["path"]=="SOURCE_CONTEXT.json")
        if hashlib.sha256(raw).hexdigest()!=expected["sha256"]:raise ValueError("source comparison checksum changed")
        context=json.loads(raw)
        for item in context["registered_comparison_outlines"]:
            if item.get("comparison_only") is not True or item.get("physical_layer") is not False:raise ValueError("native comparison must remain nonphysical")
            if not all(len(p)==3 and all(type(v) in (int,float) and math.isfinite(v) for v in p) for p in item["render_path_m"]):raise ValueError("bad comparison outline")
    return data,physical,context


def import_candidate(data,physical,context,include_reservations=False,include_cameras=False):
    import bpy
    units=bpy.context.scene.unit_settings
    if not math.isfinite(units.scale_length) or abs(units.scale_length-1)>1e-9:
        raise ValueError("Use a fresh isolated scene with scale_length=1 metre per Blender unit; no scene settings were changed")
    object_names=["SW_R07_"+mesh["id"] for mesh in physical]+["SW_R07_AXIS_"+item["id"] for item in data["axis_controls"]]
    if context:object_names += ["SW_R07_COMPARE_"+item["id"] for item in context["registered_comparison_outlines"]]
    if include_reservations:object_names += ["SW_R07_RESERVE_"+item["id"] for item in data["parcels"]]
    if include_cameras:object_names += ["SW_R07_CAMERA_"+item["id"] for item in data["cameras"]]
    if bpy.data.collections.get(COLLECTION) or any(bpy.data.objects.get(name) for name in object_names):raise ValueError("isolated R07 objects already exist; preserve them or remove intentionally")
    collections=[];objects=[];meshes=[];materials=[];curves=[];cameras=[]
    try:
        main=bpy.data.collections.new(COLLECTION);collections.append(main)
        main["classification"]="proposed_metric"
        main["source_package"]=PACKAGE_ID
        main["world_integration"]="UNRESOLVED; do not merge into authoritative world"
        main["scene_scale_length"]=units.scale_length;main["scene_unit_system"]=units.system;main["scene_length_unit"]=units.length_unit
        colors={"land":(0.54,0.65,0.48,1),"water":(0.38,0.58,0.66,1),"road":(0.20,0.25,0.29,1),"pedestrian":(0.88,0.68,0.30,1)}
        palette={}
        for key,color in colors.items():
            material=bpy.data.materials.new("SW_R07_PROPOSED_"+key);materials.append(material);material.diffuse_color=color;palette[key]=material
        for item in physical:
            mesh=bpy.data.meshes.new("SW_R07_"+item["id"]+"_DATA");meshes.append(mesh)
            mesh.from_pydata(item["vertices_m"],[],item["triangles"]);mesh.update()
            obj=bpy.data.objects.new("SW_R07_"+item["id"],mesh);objects.append(obj)
            obj["classification"]="proposed_metric";obj["physical_layer"]=True;obj["feature_id"]=item["feature_id"]
            obj["source_units"]="metres";obj["approved_for_construction"]=False
            obj.location=(0,0,0);obj.rotation_euler=(0,0,0);obj.scale=(1,1,1)
            mesh.materials.append(palette.get(item["material"],palette["road"]));main.objects.link(obj)
        for item in data["axis_controls"]:
            obj=bpy.data.objects.new("SW_R07_AXIS_"+item["id"],None);objects.append(obj)
            obj.location=item["authoring_m"];obj.empty_display_type="PLAIN_AXES";obj.empty_display_size=5
            obj["classification"]="nonphysical_synthetic_axis_control";obj["physical_layer"]=False
            obj["expected_interface_cm_before_R_T"]=item["expected_interface_cm_before_R_T"];main.objects.link(obj)
        if context:
            compare=bpy.data.collections.new("SW_R07_COMPARISON_ONLY_NO_COLLISION");collections.append(compare)
            compare["physical_layer"]=False;compare["classification"]="historical_context_only"
            main.children.link(compare)
            for item in context["registered_comparison_outlines"]:
                curve=bpy.data.curves.new("SW_R07_COMPARE_"+item["id"],"CURVE");curves.append(curve);curve.dimensions="3D"
                spline=curve.splines.new("POLY");spline.points.add(len(item["render_path_m"])-1)
                for point,coordinate in zip(spline.points,item["render_path_m"]):point.co=(*coordinate,1)
                obj=bpy.data.objects.new("SW_R07_COMPARE_"+item["id"],curve);objects.append(obj)
                obj["physical_layer"]=False;obj["classification"]="historical_comparison_only";compare.objects.link(obj)
        if include_reservations:
            reserve=bpy.data.collections.new("SW_R07_RESERVATIONS_ONLY_NO_COLLISION");collections.append(reserve)
            reserve["physical_layer"]=False;reserve["classification"]="proposed_program_review_only";main.children.link(reserve)
            for item in data["parcels"]:
                curve=bpy.data.curves.new("SW_R07_RESERVE_"+item["id"],"CURVE");curves.append(curve);curve.dimensions="3D"
                spline=curve.splines.new("POLY");ring=item["ring_xy_m"];spline.points.add(len(ring)-1)
                for point,coordinate in zip(spline.points,ring):point.co=(*coordinate[:2],2,1)
                obj=bpy.data.objects.new("SW_R07_RESERVE_"+item["id"],curve);objects.append(obj)
                obj["physical_layer"]=False;obj["classification"]="proposed_parcel_not_a_building"
                programs=[p for p in data["program_reservations"] if p["parcel_id"]==item["id"]]
                obj["program_ids"]=json.dumps([p["id"] for p in programs])
                obj["program_review_metadata"]=json.dumps(programs,ensure_ascii=False)
                obj["parent_land_id"]=item["parent_land_id"];reserve.objects.link(obj)
        if include_cameras:
            from mathutils import Matrix
            camera_collection=bpy.data.collections.new("SW_R07_CAMERAS_ONLY_NO_COLLISION");collections.append(camera_collection)
            camera_collection["physical_layer"]=False;main.children.link(camera_collection)
            for item in data["cameras"]:
                eye=item["eye_m"];target=item["target_m"];up=item["up_vector"]
                depth=[a-b for a,b in zip(eye,target)];length=math.sqrt(sum(v*v for v in depth));depth=[v/length for v in depth]
                right=[up[1]*depth[2]-up[2]*depth[1],up[2]*depth[0]-up[0]*depth[2],up[0]*depth[1]-up[1]*depth[0]]
                length=math.sqrt(sum(v*v for v in right));right=[v/length for v in right]
                actual_up=[depth[1]*right[2]-depth[2]*right[1],depth[2]*right[0]-depth[0]*right[2],depth[0]*right[1]-depth[1]*right[0]]
                width,height=item.get("image_size_px",[1512,940])
                camera=bpy.data.cameras.new("SW_R07_CAMERA_"+item["id"]);cameras.append(camera)
                camera.type="ORTHO";camera.sensor_fit="HORIZONTAL";camera.ortho_scale=item["vertical_span_m"]*width/height
                camera.clip_start=.01;camera.clip_end=30000
                obj=bpy.data.objects.new("SW_R07_CAMERA_"+item["id"],camera);objects.append(obj)
                obj.location=eye;obj.rotation_mode="QUATERNION"
                obj.rotation_quaternion=Matrix([[right[i],actual_up[i],depth[i]] for i in range(3)]).to_quaternion()
                obj["physical_layer"]=False;obj["source_camera_id"]=item["id"]
                obj["required_render_width_px"]=width;obj["required_render_height_px"]=height
                obj["required_pixel_aspect_x"]=1;obj["required_pixel_aspect_y"]=1
                obj["vertical_span_m"]=item["vertical_span_m"];obj["actual_engine_matching"]="not_tested"
                camera_collection.objects.link(obj)
        bpy.context.scene.collection.children.link(main)
        return COLLECTION
    except Exception:
        for obj in objects:bpy.data.objects.remove(obj,do_unlink=True)
        for collection in reversed(collections):bpy.data.collections.remove(collection)
        for mesh in meshes:
            if mesh.users==0:bpy.data.meshes.remove(mesh)
        for curve in curves:
            if curve.users==0:bpy.data.curves.remove(curve)
        for camera in cameras:
            if camera.users==0:bpy.data.cameras.remove(camera)
        for material in 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")
    parser.add_argument("--include-native-comparison",action="store_true")
    parser.add_argument("--include-reservations",action="store_true",help="add nonphysical parcel review curves, without buildings/collision")
    parser.add_argument("--include-cameras",action="store_true",help="add saved nonphysical cameras; leave scene camera/render settings unchanged")
    parser.add_argument("--save-blend",type=Path,help="save a copy at a NEW .blend path; existing outputs refused before scene mutation")
    args=parser.parse_args(argv)
    save_path=preflight_save_path(args.save_blend)
    data,physical,context=preflight(args.package,args.include_native_comparison)
    if args.validate_only:print(f"PASS: {len(physical)} proposed physical meshes preflighted; comparison {'opt-in' if context else 'excluded'}; Blender untouched")
    else:
        print("Created isolated "+import_candidate(data,physical,context,args.include_reservations,args.include_cameras)+"; no authoritative world placement or engine acceptance")
        if save_path:
            save_new_blend(save_path);print("Saved new isolated candidate copy: "+str(save_path))
    return 0


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