"""Procedural collection — standalone, offline Blender procedural asset generator.

Run with Blender --background --python generate_asset.py -- [--parameters JSON]
    [--output DIRECTORY] [--no-preview]. In the Text Editor use Run Script.
Only data carrying this generator's owner tag is replaced. No imported resources.
"""
import argparse
import json
import math
import sys
from itertools import pairwise
from pathlib import Path

import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector

ASSET_ID = 'breeze_fan'
OWNER = 'procedural.breeze_fan.v1'
TAG = "generator_owner"
DEFAULTS = {'detail_level': 2, 'paint_color': [0.21, 0.35, 0.32], 'accent_color': [0.68, 0.48, 0.25], 'wood_color': [0.46, 0.29, 0.16], 'paint_roughness': 0.39, 'metal_roughness': 0.26, 'wood_grain_strength': 0.6, 'surface_relief': 0.4, 'texture_resolution': 2048, 'seed': 82017, 'diameter': 0.32, 'stand_height': 0.29, 'blade_count': 5, 'grille_rings': 5, 'grille_spokes': 24, 'tilt_angle': 8}
LIMITS = {'detail_level': [1, 3], 'paint_roughness': [0.22, 0.75], 'metal_roughness': [0.18, 0.6], 'wood_grain_strength': [0, 1], 'surface_relief': [0, 1], 'seed': [0, 2147483647], 'diameter': [0.24, 0.38], 'stand_height': [0.24, 0.43], 'blade_count': [3, 7], 'grille_rings': [3, 7], 'grille_spokes': [16, 36], 'tilt_angle': [-10, 25]}
INTEGER_KEYS = ('blade_count', 'detail_level', 'grille_rings', 'grille_spokes', 'seed', 'texture_resolution')
CHOICES = {}

def validated(values):
    unknown = set(values) - set(DEFAULTS)
    if unknown:
        raise ValueError(f"Unknown parameters: {sorted(unknown)}")
    p = dict(DEFAULTS, **values)
    for key in INTEGER_KEYS:
        if type(p[key]) is not int:
            raise ValueError(f"{key} must be an integer")
    for key, choices in CHOICES.items():
        if p[key] not in choices:
            raise ValueError(f"{key} must be one of {choices}")
    for key, (low, high) in LIMITS.items():
        if isinstance(p[key], bool) or not isinstance(p[key], (float, int)):
            raise TypeError(f"{key} must be a number")
        if not low <= p[key] <= high:
            raise ValueError(f"{key} must be in [{low}, {high}]")
    if p["texture_resolution"] not in (512, 1024, 2048, 4096):
        raise ValueError("texture_resolution must be 512, 1024, 2048 or 4096")
    for key in ("paint_color", "accent_color", "wood_color"):
        rgb = p[key]
        if not isinstance(rgb, (list, tuple)) or len(rgb) != 3:
            raise ValueError(f"{key} must contain three sRGB components")
        if not all(isinstance(v, (int, float)) and not isinstance(v, bool)
                   and 0 <= v <= 1 for v in rgb):
            raise ValueError(f"{key} components must be in [0, 1]")
    return p


def owned(data):
    data[TAG] = OWNER
    return data


def owned_scene(role):
    for scene in bpy.data.scenes:
        if scene.get(TAG) == OWNER and scene.get("role") == role:
            return scene
    scene = owned(bpy.data.scenes.new(f"PA | {role}"))
    scene["role"] = role
    return scene


def clean_generated():
    # A user object is never removed because of its name or collection membership.
    for obj in list(bpy.data.objects):
        if obj.get(TAG) == OWNER:
            bpy.data.objects.remove(obj, do_unlink=True)
    for collection in list(bpy.data.collections):
        if collection.get(TAG) == OWNER and not collection.all_objects:
            bpy.data.collections.remove(collection)
    purge_unused_generated()


def purge_unused_generated():
    for bank in (bpy.data.meshes, bpy.data.curves, bpy.data.cameras,
                 bpy.data.lights, bpy.data.materials, bpy.data.images,
                 bpy.data.worlds, bpy.data.collections):
        for data in list(bank):
            if data.get(TAG) == OWNER and data.users == 0:
                bank.remove(data)


def activate(obj):
    bpy.ops.object.select_all(action="DESELECT")
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj


class Builder:
    def __init__(self, p):
        self.p = p
        self.parts = []
        self.collection = owned(bpy.data.collections.new("PA | Asset geometry"))
        bpy.context.scene.collection.children.link(self.collection)
        self.segments = {1: 40, 2: 64, 3: 96}[p["detail_level"]]
        self.bevel_steps = p["detail_level"] + 1

    def add(self, obj, name, tile):
        owned(obj)
        owned(obj.data)
        obj.name = f"PA | {name}"
        obj["surface_tile"] = tile
        for collection in list(obj.users_collection):
            collection.objects.unlink(obj)
        self.collection.objects.link(obj)
        self.parts.append(obj)
        return obj

    def apply(self, obj, modifier):
        activate(obj)
        bpy.ops.object.modifier_apply(modifier=modifier.name)

    def bevel(self, obj, width):
        if width > 0:
            modifier = obj.modifiers.new("Manufactured edge radius", "BEVEL")
            modifier.width = width
            modifier.segments = self.bevel_steps
            modifier.limit_method = "ANGLE"
            self.apply(obj, modifier)

    def mesh(self, name, vertices, faces, tile, bevel=0):
        mesh = bpy.data.meshes.new(name)
        mesh.from_pydata(vertices, [], faces)
        mesh.update()
        obj = self.add(bpy.data.objects.new(name, mesh), name, tile)
        self.bevel(obj, bevel)
        return obj

    def box(self, name, size, center, tile, bevel=0):
        bpy.ops.mesh.primitive_cube_add(size=1, location=center)
        obj = self.add(bpy.context.object, name, tile)
        obj.dimensions = size
        bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
        self.bevel(obj, min(bevel, min(size)*0.30))
        return obj

    def tube(self, name, points, radius, tile, closed=False, normal=(0, 1, 0)):
        points = [Vector(p) for p in points]
        sides = {1: 8, 2: 12, 3: 16}[self.p["detail_level"]]
        vertices, faces = [], []
        for i, point in enumerate(points):
            before = points[(i-1) % len(points)] if closed else points[max(0, i-1)]
            after = points[(i+1) % len(points)] if closed else points[min(len(points)-1, i+1)]
            tangent = (after-before).normalized()
            ref = Vector(normal)
            if abs(ref.dot(tangent)) > 0.98:
                ref = Vector((1, 0, 0))
            side = tangent.cross(ref).normalized()
            up = side.cross(tangent).normalized()
            for j in range(sides):
                a = math.tau*j/sides
                vertices.append(point+radius*(side*math.cos(a)+up*math.sin(a)))
        for i in range(len(points) if closed else len(points)-1):
            k = (i+1) % len(points)
            for j in range(sides):
                faces.append((i*sides+j, i*sides+(j+1)%sides,
                              k*sides+(j+1)%sides, k*sides+j))
        if not closed:
            faces += [tuple(range(sides-1, -1, -1)),
                      tuple((len(points)-1)*sides+j for j in range(sides))]
        return self.mesh(name, vertices, faces, tile)

    def strut(self, name, a, b, radius, tile):
        a, b = Vector(a), Vector(b)
        obj = self.cylinder(name, radius, (b-a).length, (a+b)/2, tile, axis="Z", bevel=radius*0.2)
        obj.rotation_euler = (b-a).to_track_quat("Z", "Y").to_euler()
        return obj

    def rotate(self, objects, pivot, axis, angle):
        matrix = Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(angle, 4, axis) @ Matrix.Translation(-Vector(pivot))
        for obj in objects:
            obj.matrix_world = matrix @ obj.matrix_world

    def cut(self, obj, cutter):
        modifier = obj.modifiers.new("Functional aperture", "BOOLEAN")
        modifier.operation = "DIFFERENCE"
        modifier.solver = "EXACT"
        modifier.object = cutter
        self.apply(obj, modifier)
        self.parts.remove(cutter)
        mesh = cutter.data
        bpy.data.objects.remove(cutter, do_unlink=True)
        if mesh.users == 0:
            bpy.data.meshes.remove(mesh)

    def cylinder(self, name, radius, length, center, tile, axis="Y", bevel=0,
                 vertices=None):
        bpy.ops.mesh.primitive_cylinder_add(vertices=vertices or self.segments,
                                            radius=radius, depth=length,
                                            end_fill_type="NGON", location=center)
        obj = self.add(bpy.context.object, name, tile)
        if axis == "Y":
            obj.rotation_euler.x = math.pi / 2
        elif axis == "X":
            obj.rotation_euler.y = math.pi / 2
        bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
        self.bevel(obj, min(bevel, length*0.30, radius*0.30))
        return obj

    def lathe(self, name, profile, center, tile):
        # Closed profile around Z. Zero-radius rows become real poles, not slivers.
        cx, cy, cz = center
        vertices, rings, faces = [], [], []
        for radius, depth in profile:
            if radius == 0:
                rings.append([len(vertices)])
                vertices.append((cx, cy, cz + depth))
            else:
                ring = []
                for j in range(self.segments):
                    angle = math.tau * j / self.segments
                    ring.append(len(vertices))
                    vertices.append((cx + radius * math.cos(angle),
                                     cy + radius * math.sin(angle), cz + depth))
                rings.append(ring)
        for a, b in zip(rings, rings[1:] + rings[:1]):
            if len(a) == len(b) == 1:
                continue
            for j in range(self.segments):
                k = (j + 1) % self.segments
                if len(a) == 1:
                    faces.append((a[0], b[k], b[j]))
                elif len(b) == 1:
                    faces.append((a[j], a[k], b[0]))
                else:
                    faces.append((a[j], a[k], b[k], b[j]))
        mesh = bpy.data.meshes.new(name)
        mesh.from_pydata(vertices, [], faces)
        mesh.update()
        obj = self.add(bpy.data.objects.new(name, mesh), name, tile)
        return obj

    def ring(self, name, outer, inner, depth, center, tile, bevel=0):
        obj = self.lathe(name, [(outer, 0), (inner, 0), (inner, depth),
                                (outer, depth)], center, tile)
        self.bevel(obj, bevel)
        return obj

    def sweep(self, name, points, radii, tile, wall=0.0, oval=1.0):
        """Closed solid or hollow planar sweep, with continuous lengthwise UVs."""
        points = [Vector(p) for p in points]
        segments = {1: 16, 2: 24, 3: 32}[self.p["detail_level"]]
        lengths = [0.0]
        for a, b in pairwise(points):
            lengths.append(lengths[-1]+(b-a).length)
        us = [s/lengths[-1] for s in lengths]
        vertices, faces, face_uvs = [], [], []
        layers = 2 if wall else 1
        for layer in range(layers):
            for i, point in enumerate(points):
                tangent = (points[min(i+1, len(points)-1)]-points[max(i-1, 0)]).normalized()
                across = Vector((0, 1, 0))
                up = tangent.cross(across).normalized()
                radius = float(radii[i]) - (wall if layer else 0)
                for j in range(segments):
                    a = math.tau*j/segments
                    vertices.append(point+radius*(math.cos(a)*across+oval*math.sin(a)*up))
        offset = len(points)*segments
        for layer in range(layers):
            start = layer*offset
            for i in range(len(points)-1):
                for j in range(segments):
                    k = (j+1) % segments
                    faces.append((start+i*segments+j, start+i*segments+k,
                                  start+(i+1)*segments+k, start+(i+1)*segments+j))
                    face_uvs.append([(us[i], j/segments), (us[i], (j+1)/segments),
                                     (us[i+1], (j+1)/segments), (us[i+1], j/segments)])
        for i in (0, len(points)-1):
            if wall:
                for j in range(segments):
                    k = (j+1) % segments
                    faces.append((i*segments+j, i*segments+k,
                                  offset+i*segments+k, offset+i*segments+j))
                    face_uvs.append([(us[i], j/segments), (us[i], (j+1)/segments),
                                     (us[i]+0.01 if i == 0 else us[i]-0.01, (j+1)/segments),
                                     (us[i]+0.01 if i == 0 else us[i]-0.01, j/segments)])
            else:
                faces.append(tuple(i*segments+j for j in range(segments)))
                face_uvs.append([(0.5+0.4*math.cos(math.tau*j/segments),
                                  0.5+0.4*math.sin(math.tau*j/segments)) for j in range(segments)])
        mesh = bpy.data.meshes.new(name)
        mesh.from_pydata(vertices, [], faces)
        mesh.update()
        uv = mesh.uv_layers.new(name="UVMap")
        for face, values in zip(mesh.polygons, face_uvs):
            for loop, value in zip(face.loop_indices, values):
                uv.data[loop].uv = value
        obj = self.add(bpy.data.objects.new(name, mesh), name, tile)
        obj["custom_uv"] = True
        return obj

    def text(self, name, body, size, center, tile=6, back=False):
        data = bpy.data.curves.new(name, "FONT")
        data.body = body
        data.size = size
        data.align_x = "CENTER"
        data.align_y = "CENTER"
        data.extrude = size * 0.018
        data.resolution_u = 2
        obj = self.add(bpy.data.objects.new(name, data), name, tile)
        obj.location = center
        obj.rotation_euler = (math.pi / 2, 0, math.pi if back else 0)
        activate(obj)
        bpy.ops.object.convert(target="MESH")
        owned(obj.data)
        return obj

    def finish(self, material):
        for obj in self.parts:
            activate(obj)
            mesh = obj.data
            bm = bmesh.new()
            bm.from_mesh(mesh)
            # Bfont conversion emits separate caps; weld coincident boundary vertices.
            bmesh.ops.remove_doubles(bm, verts=list(bm.verts), dist=1e-7)
            bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
            # Split only actual creases. Profile curvature remains smooth.
            for edge in bm.edges:
                if edge.is_manifold:
                    edge.smooth = edge.calc_face_angle() < math.radians(50)
            bm.to_mesh(mesh)
            bm.free()
            for face in mesh.polygons:
                face.use_smooth = True
            modifier = obj.modifiers.new("Area weighted corner normals", "WEIGHTED_NORMAL")
            modifier.keep_sharp = True
            modifier.weight = 40
            self.apply(obj, modifier)
            # Smart-project per component: islands do not overlap within a component.
            # Separate components intentionally share repeatable material tiles.
            if not obj.get("custom_uv"):
                bpy.ops.object.mode_set(mode="EDIT")
                bpy.ops.mesh.select_all(action="SELECT")
                bpy.ops.uv.smart_project(angle_limit=math.radians(66),
                                         island_margin=0.025, scale_to_bounds=True)
                bpy.ops.object.mode_set(mode="OBJECT")
            mesh.uv_layers.active.name = "UVMap"
            for face in mesh.polygons:
                tile = obj["surface_tile"]
                if obj.get("interior_tile"):
                    center_offset = Vector(obj.get("interior_center", (0, 0, 0)))
                    center = sum((mesh.vertices[i].co for i in face.vertices), Vector())/len(face.vertices)
                    center -= center_offset
                    radial_dot = face.normal.x*center.x + face.normal.y*center.y
                    if radial_dot < -0.0001 or (face.normal.z > 0.99 and center.z < 0.009):
                        tile = obj["interior_tile"]
                tx, ty = tile % 4, tile // 4
                for index in face.loop_indices:
                    loop = mesh.uv_layers.active.data[index]
                    u, v = loop.uv
                    loop.uv = ((tx + 0.035 + 0.93 * u) / 4,
                               (ty + 0.035 + 0.93 * v) / 2)
            mesh.materials.clear()
            mesh.materials.append(material)
            # Fixed triangulation makes exported tangents and roundtrip stable.
            tri = obj.modifiers.new("Stable export triangles", "TRIANGULATE")
            tri.keep_custom_normals = True
            self.apply(obj, tri)


def build_geometry(p):
    b=Builder(p)
    r=p['diameter']/2
    cz=max(p['stand_height'],r*1.2+.060)
    base=b.lathe('Weighted elliptical pedestal',[(0,.004),(r*.60,.004),(r*.66,.010),(r*.66,.020),(r*.57,.031),(0,.031)],(0,0,0),0)
    base.scale.y=1.2
    b.cylinder('Pedestal wood inset',r*.46,.004,(0,0,.032),3,axis='Z',bevel=.001)
    for sx in (-1,1):
        for sy in (-1,1):
            b.cylinder('Non slip foot',.011,.004,(sx*r*.36,sy*r*.44,.002),2,axis='Z',vertices=24)
    b.strut('Telescoping stand outer',(0,0,.026),(0,0,cz-r*1.05),.011,4)
    b.cylinder('Stand locking collar',.014,.014,(0,0,cz-r*1.17),5,axis='Z',bevel=.001)
    yoke=[(-r*1.06,0,cz),(-r*1.06,0,cz-r*.85),(-r*.85,0,cz-r*1.05),
          (r*.85,0,cz-r*1.05),(r*1.06,0,cz-r*.85),(r*1.06,0,cz)]
    b.tube('Continuous U shaped head support',yoke,.006,0)
    for sx in (-1,1):
        b.cylinder('Tilt pivot bolt',.010,.019,(sx*r*1.04,0,cz),5,axis='X',vertices=32,bevel=.001)
    b.cylinder('Speed control dial',.012,.007,(0,-r*.47,.033),5,axis='Z',bevel=.001)
    b.box('Dial pointer',(.001,.008,.001),(0,-r*.47-.002,.037),2,.0002)
    start=len(b.parts)
    b.lathe('Rear motor casing',[(0,-.074),(.022,-.074),(.032,-.064),(.034,-.012),(.029,.004),(0,.004)],(0,0,0),0)
    for j in range(p['blade_count']):
        angle=math.tau*j/p['blade_count']
        vertices=[]; faces=[]; steps=16+8*p['detail_level']
        for layer in (-1,1):
            for i in range(steps+1):
                t=i/steps
                radius=r*(.17+.71*t)
                half=.10+.29*math.sin(math.pi*t)**.7
                for edge in (-1,1):
                    a=angle+.58*t+edge*half
                    vertices.append((radius*math.cos(a),radius*math.sin(a),
                                     -.002+.012*(1-t)*edge+layer*.0012))
        offset=(steps+1)*2
        for i in range(steps):
            k=i*2
            faces.extend([(k,k+1,k+3,k+2),(k+offset,k+2+offset,k+3+offset,k+1+offset),
                          (k,k+2,k+2+offset,k+offset),(k+1,k+1+offset,k+3+offset,k+3)])
        faces += [(0,offset,offset+1,1),(2*steps,2*steps+1,2*steps+1+offset,2*steps+offset)]
        b.mesh('Swept pitched rotor blade',vertices,faces,5,bevel=.0007)
    b.lathe('Rounded rotor hub',[(0,-.016),(r*.22,-.016),(r*.24,0),(r*.21,.022),(r*.14,.030),(0,.033)],(0,0,0),0)
    b.ring('Split cage rim',r*1.015,r*.993,.012,(0,0,-.006),4,.001)
    for side in (-1,1):
        dome=.054 if side==1 else .040
        for i in range(p['grille_rings']):
            radius=r*(.18+.79*i/(p['grille_rings']-1))
            depth=side*dome*(1-(radius/r)**2)
            points=[(radius*math.cos(a),radius*math.sin(a),depth) for a in np.linspace(0,math.tau,b.segments,endpoint=False)]
            b.tube('Concentric safety cage ring',points,.00105,4,closed=True,normal=(0,0,1))
        for j in range(p['grille_spokes']):
            a=math.tau*j/p['grille_spokes']
            points=[(r*t*math.cos(a),r*t*math.sin(a),side*dome*(1-t*t)) for t in np.linspace(.16,1,14)]
            b.tube('Radial curved safety spoke',points,.0009,4,normal=(0,0,1))
    b.cylinder('Front badge',r*.17,.003,(0,0,.055),0,axis='Z',bevel=.001)
    for j in range(4):
        a=math.tau*j/4
        b.box('Cage retaining clip',(.011,.011,.017),(r*math.cos(a),r*math.sin(a),0),0,.002)
    bpy.context.view_layer.update()
    b.rotate(b.parts[start:],(0,0,0),'X',math.pi/2+math.radians(p['tilt_angle']))
    for obj in b.parts[start:]:
        obj.location.z+=cz
    return b


def write_image(name, rgb, path, color=False):
    height, width = rgb.shape[:2]
    image = owned(bpy.data.images.new(name, width=width, height=height, alpha=False))
    image.colorspace_settings.name = "sRGB" if color else "Non-Color"
    rgba = np.ones((height, width, 4), dtype=np.float32)
    rgba[:, :, :3] = rgb
    image.pixels.foreach_set(rgba.ravel())
    image.filepath_raw = str(path)
    image.file_format = "PNG"
    image.save()
    # Reload the PNG, making byte-buffer color interpretation explicit.
    image.reload()
    image.pack()
    return image


def make_textures(p, directory):
    n = p["texture_resolution"]
    tw, th = n//4, n//2
    rng = np.random.default_rng(p["seed"])
    maps = {key: np.zeros((n, n, 3), np.float32)
            for key in ("basecolor", "normal", "roughness", "metalness")}
    specs = [
        (p["paint_color"], p["paint_roughness"], 0.0),
        ([0.52, 0.55, 0.57], p["metal_roughness"]+0.10, 0.95),
        ([0.052, 0.059, 0.065], 0.70, 0.0),
        (p["wood_color"], 0.43, 0.0),
        ([0.32, 0.35, 0.38], p["metal_roughness"], 0.95),
        (p["accent_color"], p["metal_roughness"]+0.04, 0.82),
        ([0.76, 0.80, 0.79], 0.48, 0.0),
        ([0.11, 0.13, 0.14], 0.90, 0.0),
    ]
    u, v = np.meshgrid(np.arange(tw)/tw, np.arange(th)/th)
    for tile, (color, rough, metal) in enumerate(specs):
        grain = np.zeros((th, tw))
        for _ in range(7):
            a, b = rng.integers(12, 170, size=2)
            grain += np.sin(math.tau*(a*u+b*v)+rng.uniform(0, math.tau))/7
        fine = rng.uniform(-1, 1, (th, tw))
        height = grain*0.008 + fine*0.006
        color_variation = 1+grain*0.018
        if tile == 3:
            # Growth lines follow U along the carved grip, varying across its section.
            phase = rng.uniform(0, math.tau)
            warp = 1.1*np.sin(math.tau*u*2+phase)+0.19*np.sin(math.tau*u*7+v*4)
            bands = (0.5+0.5*np.sin(math.tau*(v*65+warp)))**10
            broad = np.sin(math.tau*(v*6+warp*0.15))
            strength = p["wood_grain_strength"]
            color_variation = 1-strength*(bands*0.48+broad*0.16)+fine*0.015
            height = (bands*0.035+broad*0.012+grain*0.012)*strength
        elif tile == 7:
            weave = np.sin(math.tau*u*140)*np.sin(math.tau*v*140)
            color_variation = 1+weave*0.13+fine*0.04
            height = weave*0.10+fine*0.025
        elif tile in (1, 4, 5):
            height = np.sin(math.tau*u*190)*0.018+grain*0.015
        elif tile == 6:
            height *= 0.05
        region = (slice((tile//4)*th, (tile//4+1)*th),
                  slice((tile%4)*tw, (tile%4+1)*tw))
        maps["basecolor"][region] = np.clip(
            np.array(color)[None, None, :]*color_variation[:, :, None], 0, 1)
        maps["roughness"][region] = np.clip(rough+height[:, :, None]*0.06, 0.02, 1)
        maps["metalness"][region] = metal
        # Pixel rows increase in +V in Blender; tangent normal uses OpenGL +Y.
        dx = (np.roll(height, -1, 1)-np.roll(height, 1, 1))*p["surface_relief"]
        dy = (np.roll(height, -1, 0)-np.roll(height, 1, 0))*p["surface_relief"]
        normal = np.stack((-dx, -dy, np.ones_like(dx)), axis=-1)
        normal /= np.linalg.norm(normal, axis=-1, keepdims=True)
        maps["normal"][region] = normal*0.5+0.5
    images = {}
    for name, pixels in maps.items():
        images[name] = write_image(f"PA | {name}", pixels,
                                   directory / f"asset_{ASSET_ID}_{name}.png",
                                   color=name == "basecolor")
    orm = np.ones((n, n, 3), np.float32)
    orm[:, :, 1] = maps["roughness"][:, :, 0]
    orm[:, :, 2] = maps["metalness"][:, :, 0]
    images["orm"] = write_image("PA | orm", orm,
                                 directory / f"asset_{ASSET_ID}_orm.png")
    return images


def make_material(images):
    material = owned(bpy.data.materials.new("PA | Procedural PBR atlas"))
    tree = material.node_tree
    bsdf = tree.nodes.get("Principled BSDF")
    bsdf.inputs["Roughness"].default_value = 0.5
    bsdf.inputs["Metallic"].default_value = 1
    for index, (key, socket) in enumerate((("basecolor", "Base Color"),
                                          ("normal", "Normal"), ("orm", None))):
        node = tree.nodes.new("ShaderNodeTexImage")
        node.image = images[key]
        node.label = key
        node.location = (-650, 300-index*290)
        node.interpolation = "Linear"
        if key == "normal":
            convert = tree.nodes.new("ShaderNodeNormalMap")
            convert.space = "TANGENT"
            convert.uv_map = "UVMap"
            convert.convention = "OPENGL"
            convert.location = (-300, 0)
            tree.links.new(node.outputs["Color"], convert.inputs["Color"])
            tree.links.new(convert.outputs["Normal"], bsdf.inputs[socket])
        elif key == "orm":
            separate = tree.nodes.new("ShaderNodeSeparateColor")
            separate.mode = "RGB"
            separate.location = (-300, -260)
            tree.links.new(node.outputs["Color"], separate.inputs["Color"])
            tree.links.new(separate.outputs["Green"], bsdf.inputs["Roughness"])
            tree.links.new(separate.outputs["Blue"], bsdf.inputs["Metallic"])
        else:
            tree.links.new(node.outputs["Color"], bsdf.inputs[socket])
    return material


def setup_preview(builder, p, output, render=True):
    scene = owned_scene("Studio preview")
    bpy.context.window.scene = scene
    if builder.collection.name not in scene.collection.children:
        scene.collection.children.link(builder.collection)
    scene.render.engine = "CYCLES"
    scene.cycles.samples = 48
    scene.cycles.use_denoising = True
    scene.cycles.seed = p["seed"]
    scene.render.resolution_x = 1600
    scene.render.resolution_y = 1600
    scene.render.resolution_percentage = 100
    scene.render.image_settings.file_format = "PNG"
    scene.view_settings.view_transform = "AgX"
    world = owned(bpy.data.worlds.new("PA | Neutral studio world"))
    world.node_tree.nodes.get("Background").inputs["Color"].default_value = (0.24, 0.22, 0.19, 1)
    world.node_tree.nodes.get("Background").inputs["Strength"].default_value = 0.28
    scene.world = world
    bounds = geometry_report(builder)
    scale = max(bounds["dimensions_m"])
    target = Vector([(a+b)/2 for a, b in zip(bounds["bounds_min_m"], bounds["bounds_max_m"])])
    camera_data = owned(bpy.data.cameras.new("PA | Studio camera"))
    camera = owned(bpy.data.objects.new("PA | Studio camera", camera_data))
    scene.collection.objects.link(camera)
    camera.location = target + Vector((-scale*0.90, -scale*2.7, scale*1.45))
    camera.rotation_euler = (target-camera.location).to_track_quat("-Z", "Y").to_euler()
    camera_data.type = "ORTHO"
    camera_data.ortho_scale = scale*1.38
    scene.camera = camera
    for name, location, power, size, color in (
        ("Key", (1.4, -1.8, 2.5), 520, 1.7, (1.0, 0.87, 0.72)),
        ("Fill", (-1.8, -1.0, 1.3), 380, 1.5, (0.72, 0.85, 1.0)),
        ("Rim", (0.6, 1.5, 2.0), 700, 1.2, (0.82, 0.91, 1.0)),
    ):
        data = owned(bpy.data.lights.new("PA | "+name, "AREA"))
        data.energy = power*0.24*(scale/0.7)**2
        data.shape = "DISK"
        data.size = size*scale
        data.color = color
        obj = owned(bpy.data.objects.new("PA | "+name, data))
        scene.collection.objects.link(obj)
        obj.location = Vector(location)*scale
        obj.rotation_euler = (target-obj.location).to_track_quat("-Z", "Y").to_euler()
    bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, -0.0003))
    ground = owned(bpy.context.object)
    ground.name = "PA | Preview floor (not exported)"
    owned(ground.data)
    material = owned(bpy.data.materials.new("PA | Studio floor"))
    material.node_tree.nodes.get("Principled BSDF").inputs["Base Color"].default_value = (0.17, 0.15, 0.125, 1)
    material.node_tree.nodes.get("Principled BSDF").inputs["Roughness"].default_value = 0.82
    ground.data.materials.append(material)
    scene.render.filepath = str(output / "previews" / f"asset_{ASSET_ID}_overview.png")
    if render:
        bpy.ops.render.render(write_still=True)
    return scene


def geometry_report(builder):
    vertices = [obj.matrix_world @ v.co for obj in builder.parts for v in obj.data.vertices]
    low = [min(v[i] for v in vertices) for i in range(3)]
    high = [max(v[i] for v in vertices) for i in range(3)]
    return {"objects": len(builder.parts),
            "vertices": sum(len(obj.data.vertices) for obj in builder.parts),
            "triangles": sum(len(obj.data.polygons) for obj in builder.parts),
            "bounds_min_m": low, "bounds_max_m": high,
            "dimensions_m": [b-a for a, b in zip(low, high)]}


def save_embedded(source, p):
    for name, content in (("generate_asset.py", source),
                          ("parameters.json", json.dumps(p, indent=2)+"\n")):
        text = next((t for t in bpy.data.texts
                     if t.get(TAG) == OWNER and t.get("source_role") == name), None)
        if text is None:
            text = owned(bpy.data.texts.new(name))
        text.clear()
        text.write(content)
        text["source_role"] = name
        text.use_module = False


def generate(p, output, source, preview=True):
    p = validated(p)
    output = Path(output).expanduser().resolve()
    for name in ("source", "mesh", "textures", "previews", "validation"):
        (output/name).mkdir(parents=True, exist_ok=True)
    # Check parameters before replacing anything.
    clean_generated()
    scene = owned_scene("Asset")
    bpy.context.window.scene = scene
    scene.unit_settings.system = "METRIC"
    scene.unit_settings.scale_length = 1.0
    print("PA: Generating procedural images", flush=True)
    images = make_textures(p, output/"textures")
    material = make_material(images)
    print("PA: Building parameterized asset", flush=True)
    builder = build_geometry(p)
    builder.finish(material)
    bpy.context.view_layer.update()
    report = geometry_report(builder)
    report.update({"blender_version": bpy.app.version_string, "parameters": p})
    print("PA_GEOMETRY " + json.dumps(report), flush=True)
    bpy.ops.object.select_all(action="DESELECT")
    for obj in builder.parts:
        obj.select_set(True)
    bpy.context.view_layer.objects.active = builder.parts[0]
    bpy.ops.export_scene.gltf(
        filepath=str(output/"mesh"/f"asset_{ASSET_ID}.glb"),
        export_format="GLB", use_selection=True, use_active_scene=True, export_texcoords=True,
        export_normals=True, export_tangents=True, export_materials="EXPORT",
        export_image_format="AUTO", export_cameras=False, export_lights=False,
        export_animations=False, export_yup=True, export_extras=True,
    )
    (output/"source"/"generate_asset.py").write_text(source, encoding="utf-8")
    (output/"source"/"parameters.json").write_text(json.dumps(p, indent=2)+"\n", encoding="utf-8")
    save_embedded(source, p)
    scene["parameters_json"] = json.dumps(p)
    scene["asset_dimensions_m"] = report["dimensions_m"]
    setup_preview(builder, p, output, render=preview)
    bpy.context.window.scene = scene
    for key, image in images.items():
        image.filepath = f"//../textures/asset_{ASSET_ID}_{key}.png"
    purge_unused_generated()
    # A useful material viewport and camera view are stored without external assets.
    for screen in bpy.data.screens:
        for area in screen.areas:
            if area.type == "VIEW_3D":
                area.spaces.active.shading.type = "MATERIAL"
                area.spaces.active.region_3d.view_distance = max(report["dimensions_m"])*2.5
                area.spaces.active.region_3d.view_location = tuple((a+b)/2 for a, b in zip(report["bounds_min_m"], report["bounds_max_m"]))
    old_versions = bpy.context.preferences.filepaths.save_version
    try:
        bpy.context.preferences.filepaths.save_version = 0
        bpy.ops.wm.save_as_mainfile(filepath=str(output/"source"/f"asset_{ASSET_ID}.blend"))
    finally:
        bpy.context.preferences.filepaths.save_version = old_versions
    (output/"validation"/"generation.json").write_text(json.dumps(report, indent=2)+"\n")
    print("PA_COMPLETE " + str(output), flush=True)
    return builder, report


def main():
    # -- is only parsed in background mode. UI Run Script reads the embedded JSON.
    cli = bpy.app.background and "--" in sys.argv
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--parameters", type=Path)
    parser.add_argument("--output", type=Path)
    parser.add_argument("--no-preview", action="store_true")
    args = parser.parse_args(sys.argv[sys.argv.index("--")+1:] if cli else [])
    script_path = Path(globals().get("__file__", ""))
    external = script_path.is_file() and script_path.suffix == ".py"
    if external:
        source = script_path.read_text(encoding="utf-8")
        root = script_path.resolve().parent.parent
    else:
        texts = [t for t in bpy.data.texts if t.get(TAG) == OWNER
                 and t.get("source_role") == "generate_asset.py"]
        if not texts or not bpy.data.filepath:
            raise RuntimeError("Run the external .py once or open the delivered .blend")
        source = texts[0].as_string()
        root = Path(bpy.data.filepath).resolve().parent.parent
    if args.parameters:
        values = json.loads(args.parameters.read_text(encoding="utf-8"))
    elif not external:
        text = next(t for t in bpy.data.texts if t.get(TAG) == OWNER
                    and t.get("source_role") == "parameters.json")
        values = json.loads(text.as_string())
    else:
        params = script_path.parent/"parameters.json"
        values = json.loads(params.read_text(encoding="utf-8")) if params.exists() else {}
    generate(values, args.output or root, source, preview=not args.no_preview)


if __name__ == "__main__":
    main()
