"""Crown Landmark (PI-BLD-0001-V01) exterior build toolkit, shared by all component modules.

Run inside Blender 5.2 (bpy). Units: metres. Z up. FRONT = -Y. X = local right. Origin = tower centre at finished ground.
Source of numbers: EXT R06 DesignTargets.json (proposed for blockout, not accepted). Taper/profile numbers marked PROPOSED.
"""
import math
import os
import bpy
import bmesh
from mathutils import Vector

# ---------------------------------------------------------------- targets (EXT R06) -------------
HEIGHT = 240.0
FOUNDATION = (160.0, 120.0)
DECKS = [  # z top, width (X), depth (Y)
    (18.0, 145.0, 106.0),
    (36.0, 125.0, 90.0),
    (54.0, 105.0, 76.0),
]
TOWER_BASE = (68.0, 54.0)      # envelope at +54 m
TOWER_ROOF_Z = 216.0
CROWN_TOP = 240.0
PODIUM_SPACING, TOWER_SPACING = 6.0, 4.5
ENTRY_ARCH = (18.0, 14.0)      # width, clear height
ENTRY_PORTAL = (8.0, 4.5)
CAP_ENVELOPE = (16.0, 24.0)    # central glazed cap (X, Y)
RIBS = {  # id: (foot_xy, tip_xy, tip_z)
    "R1": ((-58, -40), (-14, -13), 240.0),
    "R2": ((58, -40), (14, -13), 238.0),
    "R3": ((-64, 6), (-27, 5), 234.0),
    "R4": ((64, 6), (27, 5), 232.0),
    "R5": ((-40, 44), (-13, 19), 236.0),
    "R6": ((40, 44), (13, 19), 238.0),
}

# PROPOSED tower glass profile (not in R06). Reference images show a concave "horn" flare.
# Round-3 sweep (6 variants, mean silhouette IoU vs references): K=3.0/34x26 0.648 ... K=1.8/42x32 0.675 (best). Adopted, still PROPOSED.
TOWER_TOP = (float(os.environ.get("CL_TOP_W", 42.0)), float(os.environ.get("CL_TOP_D", 32.0)))  # PROPOSED width/depth at +216
FLARE_K = float(os.environ.get("CL_FLARE_K", 1.8))  # PROPOSED concavity exponent: 1 = straight taper, higher = more horn-like
# CL_* environment variables override the proposed profile for experiments (see sweep in the C03 notes).


def lerp(a, b, t):
    return a + (b - a) * t


def smooth(t):
    return t * t * (3 - 2 * t)


def tower_half_extents(z):
    """Half-width (X) and half-depth (Y) of the tower glass body at height z (54..216)."""
    t = min(max((z - 54.0) / (TOWER_ROOF_Z - 54.0), 0.0), 1.0)
    f = (1.0 - t) ** FLARE_K
    hx = TOWER_TOP[0] / 2 + (TOWER_BASE[0] / 2 - TOWER_TOP[0] / 2) * f
    hy = TOWER_TOP[1] / 2 + (TOWER_BASE[1] / 2 - TOWER_TOP[1] / 2) * f
    return hx, hy


# ---------------------------------------------------------------- collections / materials -------
def collection(name, parent=None):
    c = bpy.data.collections.get(name)
    if c is None:
        c = bpy.data.collections.new(name)
        (parent or bpy.context.scene.collection).children.link(c)
    return c


_PALETTE = {  # name: (rgba, metallic, roughness, emissive_strength)
    "ivory":   ((0.93, 0.89, 0.80, 1.0), 0.0, 0.45, 0.0),
    "glass":   ((0.16, 0.36, 0.52, 0.55), 0.0, 0.08, 0.0),
    "gold":    ((0.83, 0.62, 0.25, 1.0), 0.9, 0.30, 0.0),
    "amber":   ((1.00, 0.72, 0.28, 0.85), 0.0, 0.20, 1.2),
    "water":   ((0.25, 0.50, 0.62, 0.7), 0.0, 0.05, 0.0),
    "stone":   ((0.88, 0.85, 0.78, 1.0), 0.0, 0.60, 0.0),
    "parapet": ((0.45, 0.68, 0.80, 0.55), 0.0, 0.08, 0.0),
}


def mat(name):
    """Named material from the shared palette (same look in every module)."""
    key = "CL_" + name
    m = bpy.data.materials.get(key)
    if m:
        return m
    rgba, metal, rough, emit = _PALETTE[name]
    m = bpy.data.materials.new(key)
    m.use_nodes = True
    b = m.node_tree.nodes.get("Principled BSDF")
    b.inputs["Base Color"].default_value = rgba
    b.inputs["Metallic"].default_value = metal
    b.inputs["Roughness"].default_value = rough
    b.inputs["Alpha"].default_value = rgba[3]
    if emit > 0:
        b.inputs["Emission Color"].default_value = rgba
        b.inputs["Emission Strength"].default_value = emit
    m.diffuse_color = rgba            # Workbench / solid-view colour
    return m


# ---------------------------------------------------------------- mesh builders -----------------
def make_object(name, verts, faces, material, coll, smooth_shade=True, recalc=True):
    """Create a mesh object from raw verts/faces in `coll`. Returns the object."""
    me = bpy.data.meshes.new(name)
    me.from_pydata([tuple(v) for v in verts], [], [tuple(f) for f in faces])
    me.update()
    if recalc:
        bm = bmesh.new()
        bm.from_mesh(me)
        bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
        bm.to_mesh(me)
        bm.free()
    if smooth_shade:
        for p in me.polygons:
            p.use_smooth = True
    ob = bpy.data.objects.new(name, me)
    if material is not None:
        ob.data.materials.append(material)
    coll.objects.link(ob)
    return ob


def rounded_rect(w, d, r, n=6, z=0.0):
    """Closed ring of points for a rounded rectangle (counter-clockwise, seen from +Z)."""
    r = min(r, w / 2 - 1e-3, d / 2 - 1e-3)
    pts = []
    corners = [(w / 2 - r, d / 2 - r, 0), (-w / 2 + r, d / 2 - r, 90), (-w / 2 + r, -d / 2 + r, 180), (w / 2 - r, -d / 2 + r, 270)]
    for cx, cy, a0 in corners:
        for i in range(n + 1):
            a = math.radians(a0 + 90.0 * i / n)
            pts.append((cx + r * math.cos(a), cy + r * math.sin(a), z))
    return pts


def loft(rings, cap_bottom=True, cap_top=True):
    """Join equal-length closed rings (list of lists of xyz) into verts, faces."""
    n = len(rings[0])
    verts = [p for ring in rings for p in ring]
    faces = []
    for k in range(len(rings) - 1):
        for i in range(n):
            a, b = k * n + i, k * n + (i + 1) % n
            faces.append((a, b, b + n, a + n))
    if cap_bottom:
        faces.append(tuple(range(n - 1, -1, -1)))
    if cap_top:
        base = (len(rings) - 1) * n
        faces.append(tuple(range(base, base + n)))
    return verts, faces


def bezier(p0, p1, p2, p3, t):
    u = 1 - t
    return tuple(u ** 3 * a + 3 * u * u * t * b + 3 * u * t * t * c + t ** 3 * d for a, b, c, d in zip(p0, p1, p2, p3))


def blade(path_pts, widths, thicks, up=(0, 0, 1), cap=True):
    """Sweep a rectangular section along a polyline.
    path_pts: list of xyz; widths/thicks: per-point section width (side direction) and thickness (normal direction).
    The section's side axis = tangent x up (horizontal-ish); thickness axis = side x tangent."""
    rings = []
    up = Vector(up)
    n = len(path_pts)
    for i, p in enumerate(path_pts):
        a = Vector(path_pts[min(i + 1, n - 1)]) - Vector(path_pts[max(i - 1, 0)])
        tan = a.normalized()
        side = tan.cross(up)
        if side.length < 1e-6:
            side = Vector((1, 0, 0))
        side.normalize()
        nor = side.cross(tan).normalized()
        c = Vector(p)
        hw, ht = widths[i] / 2, thicks[i] / 2
        rings.append([tuple(c + side * hw + nor * ht), tuple(c - side * hw + nor * ht),
                      tuple(c - side * hw - nor * ht), tuple(c + side * hw - nor * ht)])
    return loft(rings, cap_bottom=cap, cap_top=cap)


def pointed_arch(width, height, n=16):
    """Half-plane points (x, z) of a pointed (two-centre) arch, springing at z=0, apex at z=height."""
    hw = width / 2
    # two-centre arch: circle centres at x=+-c on the springing line, radius R, apex at height
    # R^2 = (hw+c)^2 ; apex: height^2 + c^2 = R^2 -> c = (height^2 - hw^2) / (2*hw)
    c = (height ** 2 - hw ** 2) / (2 * hw)
    R = hw + c
    pts = []
    a_max = math.atan2(height, c)
    for i in range(n + 1):  # right side from springing to apex
        a = a_max * i / n
        pts.append((-c + R * math.cos(a), R * math.sin(a)))
    return pts  # right half: starts at (hw, 0) and ends at (0, height)


def finish(coll_name):
    """Return objects of a collection (for module self-tests)."""
    return list(collection(coll_name).objects)
