"""Assemble Crown Landmark exterior: run component modules, save .blend, render standard views.

Usage (headless):
  blender.exe --background --factory-startup --python assemble.py -- [--modules a,b,c] [--out DIR] [--tag NAME] [--no-render]
Each module is modules/<name>.py exposing build(). Modules may be run alone (--modules ribs) for self-test.
Renders: <out>/<tag>_{front,rear,left,right,top,elevated,elevated_rear}.png  (Workbench, material colours)
"""
import sys, os, math, importlib, json, time
import bpy
from mathutils import Vector

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, "modules"))
import cl_common as C

argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
def arg(name, default=None):
    return argv[argv.index(name) + 1] if name in argv else default

ALL = ["podium", "tower", "ribs", "entrance", "crown"]
mods = (arg("--modules") or ",".join(ALL)).split(",")
out = arg("--out", os.path.join(HERE, "..", "out"))
tag = arg("--tag", "assembly")
os.makedirs(out, exist_ok=True)

bpy.ops.wm.read_factory_settings(use_empty=True)
sc = bpy.context.scene
sc.unit_settings.system = "METRIC"
sc.unit_settings.scale_length = 1.0

report = {"modules": {}}
for m in mods:
    path = os.path.join(HERE, "modules", m + ".py")
    if not os.path.exists(path):
        report["modules"][m] = "MISSING"
        continue
    t0 = time.time()
    try:
        mod = importlib.import_module(m)
        importlib.reload(mod)
        mod.build()
        n = len(C.collection(getattr(mod, "COLLECTION", m)).objects)
        report["modules"][m] = {"objects": n, "seconds": round(time.time() - t0, 2)}
    except Exception as e:
        import traceback
        report["modules"][m] = {"error": repr(e), "trace": traceback.format_exc()[-1500:]}

# bounds of everything built
pts = [ob.matrix_world @ Vector(c) for ob in bpy.data.objects if ob.type == "MESH" for c in ob.bound_box]
if pts:
    lo = [min(p[i] for p in pts) for i in range(3)]; hi = [max(p[i] for p in pts) for i in range(3)]
    report["bounds_m"] = {"min": [round(v, 2) for v in lo], "max": [round(v, 2) for v in hi]}
    report["objects"] = sum(1 for o in bpy.data.objects if o.type == "MESH")
    report["triangles"] = sum(len(o.data.polygons) for o in bpy.data.objects if o.type == "MESH")

blend_path = os.path.abspath(os.path.join(out, tag + ".blend"))
bpy.ops.wm.save_as_mainfile(filepath=blend_path)
report["blend"] = blend_path

if "--no-render" not in argv:
    sc.render.engine = "BLENDER_WORKBENCH"
    sc.render.resolution_x, sc.render.resolution_y = 1024, 1536
    sc.render.film_transparent = False
    sh = sc.display.shading
    sh.light = "STUDIO"; sh.color_type = "MATERIAL"; sh.show_cavity = False; sh.show_object_outline = True
    sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.80, 0.80, 0.84)
    sc.view_settings.view_transform = "Standard"

    def cam(name, loc, rot=None, target=None, ortho=None, lens=35):
        cd = bpy.data.cameras.new(name)
        if ortho:
            cd.type = "ORTHO"; cd.ortho_scale = ortho
        else:
            cd.lens = lens
        cd.clip_end = 3000
        co = bpy.data.objects.new(name, cd)
        sc.collection.objects.link(co)
        co.location = loc
        if rot is not None:
            co.rotation_euler = tuple(math.radians(a) for a in rot)
        if target is not None:
            d = Vector(target) - Vector(loc)
            co.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
        return co

    views = {
        "front": cam("front", (0, -600, 125), (90, 0, 0), ortho=290),
        "rear": cam("rear", (0, 600, 125), (90, 0, 180), ortho=290),
        "left": cam("left", (-600, 0, 125), (90, 0, -90), ortho=290),
        "right": cam("right", (600, 0, 125), (90, 0, 90), ortho=290),
        "top": cam("top", (0, 0, 600), (0, 0, 0), ortho=200),
        "elevated": cam("elevated", (-250, -330, 230), target=(0, 0, 105), lens=48),
        "elevated_rear": cam("elevated_rear", (250, 330, 230), target=(0, 0, 105), lens=48),
    }
    sun = bpy.data.lights.new("sun", "SUN"); so = bpy.data.objects.new("sun", sun); sc.collection.objects.link(so)
    so.rotation_euler = (math.radians(50), 0, math.radians(35))
    for name, co in views.items():
        sc.camera = co
        sc.render.resolution_x, sc.render.resolution_y = (1536, 1536) if name == "top" else (1024, 1536)
        sc.render.filepath = os.path.abspath(os.path.join(out, f"{tag}_{name}.png"))
        bpy.ops.render.render(write_still=True)
    report["renders"] = [f"{tag}_{n}.png" for n in views]

with open(os.path.join(out, tag + "_report.json"), "w") as f:
    json.dump(report, f, indent=1)
print("ASSEMBLE_DONE", json.dumps(report)[:600])
