"""
build_scene.py - STRATON FR-74 portable two-reel field recorder (fictional, 1970s style)

Recreates the complete product-visualisation scene from a clean Blender session:
geometry, procedural materials, modifiers, geometry-nodes dial scales, studio,
lights, cameras, the frame 1-120 animation and an exploded technical view scene.

Usage (Blender 5.2, tested):
  blender -b --factory-startup --python build_scene.py -- [options]

Options (after the "--"):
  --render          render hero.png, detail.png and exploded.png
  --anim            also render a small animation preview (anim_preview.mp4)
  --samples N       Cycles samples for stills (default 384)
  --cpu             force CPU rendering (default: first available GPU backend)
  --preview         quick low resolution test renders (prefix preview_)
  --outdir PATH     output directory (default: folder of this script)

All units are metres. Everything is built procedurally; no external files.
"""

import bpy
import bmesh
import math
import os
import sys
from math import radians, pi, sin, cos, atan2, asin, sqrt
from mathutils import Vector, Matrix, Euler
from mathutils.geometry import tessellate_polygon

# ---------------------------------------------------------------------------
# Arguments
# ---------------------------------------------------------------------------
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []


def _arg(name, default=None, cast=str):
    if name in argv:
        i = argv.index(name)
        if i + 1 < len(argv):
            return cast(argv[i + 1])
    return default


DO_RENDER = "--render" in argv
DO_ANIM = "--anim" in argv
FORCE_CPU = "--cpu" in argv
PREVIEW = "--preview" in argv
SAMPLES = _arg("--samples", 384, int)
_here = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
OUT_DIR = os.path.abspath(_arg("--outdir", _here))
os.makedirs(OUT_DIR, exist_ok=True)

FPS = 24
FRAME_START, FRAME_END = 1, 120
TAPE_SPEED = 0.095          # 9.5 cm/s (3 3/4 ips) field speed
TRANSPORT_START, TRANSPORT_FULL = 40, 52

# ---------------------------------------------------------------------------
# Global dimensions (metres)
# ---------------------------------------------------------------------------
W, D, R_CORNER = 0.360, 0.280, 0.012
Z_FEET = 0.012
Z_SEAM = 0.024            # lower bumper band / upper case seam
Z_BODY_TOP = 0.102
Z_DECK = 0.106            # top of deck plate
Z_CTRL = 0.1075           # top of control plate
Z_TAPE = 0.118            # tape centre line height
TAPE_W = 0.00635          # 1/4 inch tape
TAPE_T = 0.0002           # visual tape thickness
TOFF = 0.00015            # path offset from roller surfaces (half tape + clearance)
Y_TAPE = -0.030           # straight tape run in front of the heads
LID_H = 0.040
LID_OPEN_DEG = 78.0
HINGE = Vector((0.0, 0.1428, Z_BODY_TOP))

REEL_L = Vector((-0.090, 0.055, 0.0))
REEL_R = Vector((0.090, 0.055, 0.0))
REEL_RADIUS = 0.0635      # 5 inch reels
HUB_R = 0.0165
PACK_SUPPLY = 0.044
PACK_TAKEUP = 0.030
GUIDE_R = 0.006
G1 = Vector((-0.122, Y_TAPE + GUIDE_R + TOFF, 0))
G2 = Vector((0.122, Y_TAPE + GUIDE_R + TOFF, 0))
CAPSTAN_R = 0.0025
CAPSTAN = Vector((0.050, Y_TAPE + CAPSTAN_R + TOFF, 0))
PINCH_R = 0.0105
PINCH = Vector((0.050, Y_TAPE - PINCH_R - TOFF, 0))
PINCH_PIVOT = Vector((0.074, -0.052, 0))


# ---------------------------------------------------------------------------
# Scene reset
# ---------------------------------------------------------------------------
def reset():
    try:
        bpy.ops.wm.read_homefile(use_empty=True)
    except Exception:
        pass
    for coll in (bpy.data.objects, bpy.data.meshes, bpy.data.materials, bpy.data.curves,
                 bpy.data.lights, bpy.data.cameras, bpy.data.node_groups, bpy.data.collections):
        for b in list(coll):
            coll.remove(b)


reset()
SCENE = bpy.context.scene
SCENE.name = "FR74_Studio"
SCENE.unit_settings.system = 'METRIC'
SCENE.unit_settings.scale_length = 1.0


# ---------------------------------------------------------------------------
# Collections
# ---------------------------------------------------------------------------
def make_coll(name, parent=None):
    c = bpy.data.collections.new(name)
    (parent or SCENE.collection).children.link(c)
    return c


C_REC = make_coll("REC_FieldRecorder")
C_HOUSING = make_coll("REC_Housing", C_REC)
C_LID = make_coll("REC_Lid", C_REC)
C_DECK = make_coll("REC_Deck", C_REC)
C_TRANSPORT = make_coll("REC_Transport", C_REC)
C_REELS = make_coll("REC_Reels", C_REC)
C_TAPE = make_coll("REC_Tape", C_REC)
C_CONTROLS = make_coll("REC_Controls", C_REC)
C_METERS = make_coll("REC_VU_Meters", C_REC)
C_MARKINGS = make_coll("REC_Markings", C_REC)
C_HARDWARE = make_coll("REC_Hardware", C_REC)
C_CUTTERS = make_coll("REC_BooleanCutters", C_REC)
C_RIGS = make_coll("REC_Rig_Pivots", C_REC)
C_STUDIO = make_coll("STUDIO_Set")
C_LIGHTS = make_coll("STUDIO_Lights")
C_CAMS = make_coll("CAMERAS")

# explode offsets per collection (used for the exploded technical view scene)
EXPLODE = {
    "REC_Housing": (0, 0, 0.0),
    "REC_Hardware": (0, 0, 0.0),
    "REC_Deck": (0, 0, 0.12),
    "REC_VU_Meters": (0, 0, 0.12),
    "REC_Controls": (0, 0, 0.20),
    "REC_Transport": (0, 0, 0.27),
    "REC_Tape": (0, 0, 0.27),
    "REC_Reels": (0, 0, 0.34),
    "REC_Lid": (0, 0, 0.47),
    "REC_Markings": (0, 0, 0.0),
}

# ---------------------------------------------------------------------------
# Materials (procedural only)
# ---------------------------------------------------------------------------
MATS = {}


def _principled(name, color, rough, metal=0.0):
    m = bpy.data.materials.new(name)
    if not m.node_tree: m.use_nodes = True
    nt = m.node_tree
    b = nt.nodes.get("Principled BSDF")
    b.inputs["Base Color"].default_value = (*color, 1.0)
    b.inputs["Roughness"].default_value = rough
    b.inputs["Metallic"].default_value = metal
    m.diffuse_color = (*color, 1.0)
    m.roughness = rough
    m.metallic = metal
    MATS[name] = m
    return m, nt, b


def _set(b, key, val):
    if key in b.inputs:
        b.inputs[key].default_value = val


def mat_brushed(name, color, rough=(0.24, 0.36), metal=1.0, coat=0.0, scale=(6.0, 2500.0, 2500.0),
                bump=0.12):
    """Linear brushed metal: stretched noise drives roughness and a fine bump."""
    m, nt, b = _principled(name, color, sum(rough) / 2, metal)
    N, L = nt.nodes, nt.links
    tc = N.new("ShaderNodeTexCoord")
    mp = N.new("ShaderNodeMapping")
    mp.inputs["Scale"].default_value = scale
    nz = N.new("ShaderNodeTexNoise")
    nz.inputs["Scale"].default_value = 1.0
    nz.inputs["Detail"].default_value = 6.0
    nz.inputs["Roughness"].default_value = 0.65
    L.new(tc.outputs["Object"], mp.inputs["Vector"])
    L.new(mp.outputs["Vector"], nz.inputs["Vector"])
    # large scale smudge variation
    nz2 = N.new("ShaderNodeTexNoise")
    nz2.inputs["Scale"].default_value = 18.0
    nz2.inputs["Detail"].default_value = 3.0
    L.new(tc.outputs["Object"], nz2.inputs["Vector"])
    mix = N.new("ShaderNodeMath")
    mix.operation = 'MULTIPLY_ADD'
    L.new(nz2.outputs["Fac"], mix.inputs[0])
    mix.inputs[1].default_value = 0.35
    L.new(nz.outputs["Fac"], mix.inputs[2])
    mr = N.new("ShaderNodeMapRange")
    mr.inputs["From Min"].default_value = 0.45
    mr.inputs["From Max"].default_value = 0.85
    mr.inputs["To Min"].default_value = rough[0]
    mr.inputs["To Max"].default_value = rough[1]
    L.new(mix.outputs[0], mr.inputs["Value"])
    L.new(mr.outputs["Result"], b.inputs["Roughness"])
    bp = N.new("ShaderNodeBump")
    bp.inputs["Strength"].default_value = bump
    bp.inputs["Distance"].default_value = 0.00005
    L.new(nz.outputs["Fac"], bp.inputs["Height"])
    L.new(bp.outputs["Normal"], b.inputs["Normal"])
    if coat:
        _set(b, "Coat Weight", coat)
        _set(b, "Coat Roughness", 0.18)
    return m


def mat_spun(name, color, rough=0.2):
    """Spun / turned metal with radial anisotropy and fine concentric lathe rings."""
    m, nt, b = _principled(name, color, rough, 1.0)
    N, L = nt.nodes, nt.links
    _set(b, "Anisotropic", 0.75)
    tg = N.new("ShaderNodeTangent")
    tg.direction_type = 'RADIAL'
    tg.axis = 'Z'
    L.new(tg.outputs["Tangent"], b.inputs["Tangent"])
    tc = N.new("ShaderNodeTexCoord")
    wv = N.new("ShaderNodeTexWave")
    wv.wave_type = 'RINGS'
    wv.rings_direction = 'SPHERICAL'
    wv.inputs["Scale"].default_value = 1800.0
    wv.inputs["Distortion"].default_value = 0.6
    L.new(tc.outputs["Object"], wv.inputs["Vector"])
    bp = N.new("ShaderNodeBump")
    bp.inputs["Strength"].default_value = 0.05
    bp.inputs["Distance"].default_value = 0.00002
    L.new(wv.outputs["Fac"], bp.inputs["Height"])
    L.new(bp.outputs["Normal"], b.inputs["Normal"])
    return m


def mat_plastic(name, color, rough, coat=0.0, micro=0.03):
    m, nt, b = _principled(name, color, rough, 0.0)
    N, L = nt.nodes, nt.links
    if coat:
        _set(b, "Coat Weight", coat)
        _set(b, "Coat Roughness", 0.08)
    if micro:
        tc = N.new("ShaderNodeTexCoord")
        nz = N.new("ShaderNodeTexNoise")
        nz.inputs["Scale"].default_value = 2500.0
        nz.inputs["Detail"].default_value = 4.0
        L.new(tc.outputs["Object"], nz.inputs["Vector"])
        bp = N.new("ShaderNodeBump")
        bp.inputs["Strength"].default_value = micro
        bp.inputs["Distance"].default_value = 0.00003
        L.new(nz.outputs["Fac"], bp.inputs["Height"])
        L.new(bp.outputs["Normal"], b.inputs["Normal"])
        mr = N.new("ShaderNodeMapRange")
        mr.inputs["To Min"].default_value = rough * 0.85
        mr.inputs["To Max"].default_value = rough * 1.2
        nz2 = N.new("ShaderNodeTexNoise")
        nz2.inputs["Scale"].default_value = 40.0
        L.new(tc.outputs["Object"], nz2.inputs["Vector"])
        L.new(nz2.outputs["Fac"], mr.inputs["Value"])
        L.new(mr.outputs["Result"], b.inputs["Roughness"])
    return m


def mat_rubber(name):
    m, nt, b = _principled(name, (0.014, 0.014, 0.015), 0.68)
    N, L = nt.nodes, nt.links
    tc = N.new("ShaderNodeTexCoord")
    vo = N.new("ShaderNodeTexVoronoi")
    vo.inputs["Scale"].default_value = 3500.0
    L.new(tc.outputs["Object"], vo.inputs["Vector"])
    bp = N.new("ShaderNodeBump")
    bp.inputs["Strength"].default_value = 0.12
    bp.inputs["Distance"].default_value = 0.00003
    L.new(vo.outputs["Distance"], bp.inputs["Height"])
    L.new(bp.outputs["Normal"], b.inputs["Normal"])
    _set(b, "Sheen Weight", 0.05)
    return m


def mat_tape(name):
    m, nt, b = _principled(name, (0.085, 0.045, 0.022), 0.42)
    N, L = nt.nodes, nt.links
    tc = N.new("ShaderNodeTexCoord")
    wv = N.new("ShaderNodeTexWave")
    wv.wave_type = 'RINGS'
    wv.rings_direction = 'SPHERICAL'
    wv.inputs["Scale"].default_value = 700.0
    wv.inputs["Distortion"].default_value = 2.0
    wv.inputs["Detail"].default_value = 3.0
    L.new(tc.outputs["Object"], wv.inputs["Vector"])
    mr = N.new("ShaderNodeMapRange")
    mr.inputs["To Min"].default_value = 0.30
    mr.inputs["To Max"].default_value = 0.55
    L.new(wv.outputs["Fac"], mr.inputs["Value"])
    L.new(mr.outputs["Result"], b.inputs["Roughness"])
    ramp = N.new("ShaderNodeValToRGB")
    ramp.color_ramp.elements[0].color = (0.032, 0.016, 0.008, 1)
    ramp.color_ramp.elements[1].color = (0.052, 0.027, 0.013, 1)
    L.new(wv.outputs["Fac"], ramp.inputs["Fac"])
    L.new(ramp.outputs["Color"], b.inputs["Base Color"])
    _set(b, "Sheen Weight", 0.15)
    return m


def mat_glass(name):
    m, nt, b = _principled(name, (0.95, 0.97, 0.97), 0.02)
    N, L = nt.nodes, nt.links
    _set(b, "Transmission Weight", 1.0)
    _set(b, "IOR", 1.49)
    out = N.get("Material Output")
    lp = N.new("ShaderNodeLightPath")
    tr = N.new("ShaderNodeBsdfTransparent")
    mx = N.new("ShaderNodeMixShader")
    L.new(lp.outputs["Is Shadow Ray"], mx.inputs["Fac"])
    L.new(b.outputs["BSDF"], mx.inputs[1])
    L.new(tr.outputs["BSDF"], mx.inputs[2])
    L.new(mx.outputs["Shader"], out.inputs["Surface"])
    m.diffuse_color = (0.8, 0.9, 0.95, 0.25)
    return m


def mat_vu_face(name):
    m, nt, b = _principled(name, (0.86, 0.80, 0.62), 0.6)
    _set(b, "Emission Color", (1.0, 0.82, 0.55, 1.0))
    _set(b, "Emission Strength", 0.35)
    N, L = nt.nodes, nt.links
    tc = N.new("ShaderNodeTexCoord")
    nz = N.new("ShaderNodeTexNoise")
    nz.inputs["Scale"].default_value = 6000.0
    L.new(tc.outputs["Object"], nz.inputs["Vector"])
    bp = N.new("ShaderNodeBump")
    bp.inputs["Strength"].default_value = 0.05
    L.new(nz.outputs["Fac"], bp.inputs["Height"])
    L.new(bp.outputs["Normal"], b.inputs["Normal"])
    return m


def mat_felt(name):
    m, nt, b = _principled(name, (0.020, 0.022, 0.021), 1.0)
    _set(b, "Sheen Weight", 0.25)
    _set(b, "Sheen Roughness", 0.6)
    N, L = nt.nodes, nt.links
    tc = N.new("ShaderNodeTexCoord")
    nz = N.new("ShaderNodeTexNoise")
    nz.inputs["Scale"].default_value = 4000.0
    nz.inputs["Detail"].default_value = 8.0
    L.new(tc.outputs["Object"], nz.inputs["Vector"])
    bp = N.new("ShaderNodeBump")
    bp.inputs["Strength"].default_value = 0.4
    L.new(nz.outputs["Fac"], bp.inputs["Height"])
    L.new(bp.outputs["Normal"], b.inputs["Normal"])
    return m


def mat_backdrop(name):
    m, nt, b = _principled(name, (0.085, 0.086, 0.09), 0.7)
    return m


M_ALU = mat_brushed("M_Alu_Brushed_Natural", (0.80, 0.80, 0.78), (0.22, 0.34))
M_CASE = mat_brushed("M_Alu_Anodized_Gunmetal", (0.16, 0.165, 0.175), (0.30, 0.42), coat=0.25)
M_BLACK_ANOD = mat_brushed("M_Alu_Anodized_Black", (0.028, 0.028, 0.030), (0.32, 0.44), coat=0.2)
M_SPUN = mat_spun("M_Alu_Spun_Reel", (0.84, 0.84, 0.85), 0.18)
M_CHROME = _principled("M_Steel_Chrome", (0.90, 0.90, 0.91), 0.06, 1.0)[0]
M_STEEL = mat_brushed("M_Steel_Ground", (0.72, 0.72, 0.74), (0.10, 0.18), scale=(4000.0, 4000.0, 8.0),
                      bump=0.05)
M_HEAD = _principled("M_Mumetal_Head", (0.74, 0.71, 0.66), 0.12, 1.0)[0]
M_RUBBER = mat_rubber("M_Rubber_Black")
M_BAKELITE = mat_plastic("M_Bakelite_Black", (0.011, 0.011, 0.012), 0.24, coat=0.4)
M_RED = mat_plastic("M_Plastic_Red", (0.55, 0.035, 0.025), 0.3, coat=0.5)
M_TAPE = mat_tape("M_Tape_Oxide")
M_GLASS = mat_glass("M_Acrylic_Lens")
M_VU = mat_vu_face("M_VU_Face_Card")
M_INK_W = mat_plastic("M_Ink_White", (0.80, 0.80, 0.77), 0.5, micro=0.0)
M_INK_K = mat_plastic("M_Ink_Black", (0.012, 0.012, 0.013), 0.55, micro=0.0)
M_INK_R = mat_plastic("M_Ink_Red", (0.62, 0.04, 0.03), 0.5, micro=0.0)
M_RECESS = _principled("M_Recess_Dark", (0.018, 0.018, 0.02), 0.6, 0.3)[0]
M_FELT = mat_felt("M_Felt_Lining")
M_LAMP = mat_plastic("M_Lamp_Jewel", (0.8, 0.05, 0.02), 0.05, micro=0.0)
_set(M_LAMP.node_tree.nodes["Principled BSDF"], "Transmission Weight", 0.6)
_set(M_LAMP.node_tree.nodes["Principled BSDF"], "Emission Color", (1.0, 0.08, 0.02, 1))
_set(M_LAMP.node_tree.nodes["Principled BSDF"], "Emission Strength", 1.5)
M_BACKDROP = mat_backdrop("M_Studio_Backdrop")


# ---------------------------------------------------------------------------
# Geometry helpers
# ---------------------------------------------------------------------------
def rrect(cx, cy, w, h, r, seg=8):
    """Rounded rectangle (CCW list of 2D points)."""
    r = min(r, w / 2 - 1e-6, h / 2 - 1e-6)
    pts = []
    corners = [(cx + w / 2 - r, cy - h / 2 + r, -90), (cx + w / 2 - r, cy + h / 2 - r, 0),
               (cx - w / 2 + r, cy + h / 2 - r, 90), (cx - w / 2 + r, cy - h / 2 + r, 180)]
    for (x, y, a0) in corners:
        if r <= 1e-6:
            pts.append((x, y))
            continue
        for i in range(seg + 1):
            a = radians(a0 + 90 * i / seg)
            pts.append((x + r * cos(a), y + r * sin(a)))
    return pts


def circle(cx, cy, r, n=48, a0=0.0):
    return [(cx + r * cos(a0 + 2 * pi * i / n), cy + r * sin(a0 + 2 * pi * i / n)) for i in range(n)]


def arc_band(cx, cy, r0, r1, a0, a1, n=24):
    """Annular sector polygon, angles in radians."""
    outer = [(cx + r1 * cos(a0 + (a1 - a0) * i / n), cy + r1 * sin(a0 + (a1 - a0) * i / n)) for i in range(n + 1)]
    inner = [(cx + r0 * cos(a1 - (a1 - a0) * i / n), cy + r0 * sin(a1 - (a1 - a0) * i / n)) for i in range(n + 1)]
    return outer + inner


def _signed_area(p):
    return 0.5 * sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))


def smooth_poly(p, it=2):
    """Chaikin corner cutting - rounds the corners of a closed polygon."""
    for _ in range(it):
        q = []
        n = len(p)
        for i in range(n):
            a, b = p[i], p[(i + 1) % n]
            q.append((0.75 * a[0] + 0.25 * b[0], 0.75 * a[1] + 0.25 * b[1]))
            q.append((0.25 * a[0] + 0.75 * b[0], 0.25 * a[1] + 0.75 * b[1]))
        p = q
    return p


def _finish_mesh(me, smooth=True, angle=35):
    bm = bmesh.new()
    bm.from_mesh(me)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-7)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(me)
    bm.free()
    if smooth:
        me.shade_smooth()
        me.set_sharp_from_angle(angle=radians(angle))
    return me


def profile_mesh(name, loops, z0, z1, bottom=True, top=True, smooth=True):
    """Extrude a 2D outline with optional holes (loops[0] outer, rest holes) from z0 to z1."""
    loops = [list(l) for l in loops]
    if _signed_area(loops[0]) < 0:
        loops[0].reverse()
    for h in loops[1:]:
        if _signed_area(h) > 0:
            h.reverse()
    verts, faces, starts = [], [], []
    for lp in loops:
        starts.append((len(verts), len(lp)))
        verts += [(x, y, z0) for x, y in lp]
    nb = len(verts)
    verts += [(x, y, z1) for x, y, _ in verts[:nb]]
    tris = tessellate_polygon([[(x, y, 0) for x, y in lp] for lp in loops])
    for t in tris:
        if bottom:
            faces.append((t[0], t[2], t[1]))
        if top:
            faces.append((t[0] + nb, t[1] + nb, t[2] + nb))
    for s, n in starts:
        for i in range(n):
            a, b = s + i, s + (i + 1) % n
            faces.append((a, b, b + nb, a + nb))
    me = bpy.data.meshes.new(name)
    me.from_pydata(verts, [], faces)
    if bottom and top:
        _finish_mesh(me, smooth)
    else:
        if smooth:
            me.shade_smooth()
            me.set_sharp_from_angle(angle=radians(35))
    return me


def lathe_mesh(name, prof, seg=64, closed=False, knurl=None, smooth=True, angle=35):
    """Revolve a (r, z) profile around Z. knurl=(count, depth, zmin, zmax)."""
    verts, faces, rings = [], [], []
    for (r, z) in prof:
        if r < 1e-8:
            rings.append([len(verts)])
            verts.append((0.0, 0.0, z))
            continue
        ring = []
        for i in range(seg):
            a = 2 * pi * i / seg
            rr = r
            if knurl and knurl[2] <= z <= knurl[3]:
                rr = r - knurl[1] * (0.5 + 0.5 * cos(knurl[0] * a)) ** 2
            ring.append(len(verts))
            verts.append((rr * cos(a), rr * sin(a), z))
        rings.append(ring)
    pairs = list(zip(rings, rings[1:]))
    if closed:
        pairs.append((rings[-1], rings[0]))
    for A, B in pairs:
        if len(A) == 1 and len(B) == 1:
            continue
        if len(A) == 1:
            for i in range(seg):
                faces.append((A[0], B[(i + 1) % seg], B[i]))
        elif len(B) == 1:
            for i in range(seg):
                faces.append((A[i], A[(i + 1) % seg], B[0]))
        else:
            for i in range(seg):
                faces.append((A[i], A[(i + 1) % seg], B[(i + 1) % seg], B[i]))
    me = bpy.data.meshes.new(name)
    me.from_pydata(verts, [], faces)
    return _finish_mesh(me, smooth, angle)


def box_mesh(name, sx, sy, sz):
    bm = bmesh.new()
    bmesh.ops.create_cube(bm, size=1.0)
    for v in bm.verts:
        v.co = Vector((v.co.x * sx, v.co.y * sy, v.co.z * sz))
    me = bpy.data.meshes.new(name)
    bm.to_mesh(me)
    bm.free()
    me.shade_smooth()
    me.set_sharp_from_angle(angle=radians(35))
    return me


def flat_mesh(name, polys, thick=0.00005):
    """Several separate thin printed polygons combined into one mesh (local XY, +Z up)."""
    verts, faces = [], []
    for p in polys:
        p = list(p)
        if _signed_area(p) < 0:
            p.reverse()
        s = len(verts)
        n = len(p)
        verts += [(x, y, 0.0) for x, y in p]
        verts += [(x, y, thick) for x, y in p]
        for t in tessellate_polygon([[(x, y, 0) for x, y in p]]):
            faces.append((s + t[0], s + t[2], s + t[1]))
            faces.append((s + n + t[0], s + n + t[1], s + n + t[2]))
        for i in range(n):
            a, b = s + i, s + (i + 1) % n
            faces.append((a, b, b + n, a + n))
    me = bpy.data.meshes.new(name)
    me.from_pydata(verts, [], faces)
    return _finish_mesh(me, smooth=False)


def add_obj(name, data, coll, mat=None, loc=(0, 0, 0), rot=(0, 0, 0), parent=None):
    ob = bpy.data.objects.new(name, data)
    coll.objects.link(ob)
    ob.location = loc
    ob.rotation_euler = rot
    if mat is not None and data is not None and hasattr(data, "materials"):
        if len(data.materials) == 0:
            data.materials.append(mat)
    if parent is not None:
        set_parent(ob, parent)
    return ob


def world_matrix(ob):
    if ob.parent is None:
        return ob.matrix_basis.copy()
    return world_matrix(ob.parent) @ ob.matrix_parent_inverse @ ob.matrix_basis


def set_parent(child, par):
    child.parent = par
    child.matrix_parent_inverse = world_matrix(par).inverted()


def empty(name, loc, coll=None, size=0.02, parent=None, kind='PLAIN_AXES'):
    e = bpy.data.objects.new(name, None)
    (coll or C_RIGS).objects.link(e)
    e.empty_display_type = kind
    e.empty_display_size = size
    e.location = loc
    if parent:
        set_parent(e, parent)
    return e


def bevel(ob, w=0.001, seg=3, angle=35, harden=True):
    m = ob.modifiers.new("Bevel", 'BEVEL')
    m.width = w
    m.segments = seg
    m.limit_method = 'ANGLE'
    m.angle_limit = radians(angle)
    m.use_clamp_overlap = True
    m.harden_normals = harden
    wn = ob.modifiers.new("WeightedNormal", 'WEIGHTED_NORMAL')
    wn.keep_sharp = True
    return m


def text(name, body, size, loc, rot=(0, 0, 0), mat=None, coll=None, align='CENTER', valign='CENTER',
         extrude=0.00003, spacing=1.0, parent=None):
    cu = bpy.data.curves.new(name, 'FONT')
    cu.body = body
    cu.size = size
    cu.align_x = align
    cu.align_y = valign
    cu.extrude = extrude
    cu.space_character = spacing
    cu.materials.append(mat or M_INK_W)
    ob = add_obj(name, cu, coll or C_MARKINGS, None, loc, rot, parent)
    return ob


ROT_FRONT = (radians(90), 0, 0)        # local +Z -> world -Y
ROT_RIGHT = (radians(90), 0, radians(90))   # local +Z -> world +X
ROT_LEFT = (radians(90), 0, radians(-90))   # local +Z -> world -X
ROT_DOWN = (radians(180), 0, 0)        # local +Z -> world -Z (lid underside)


def drive(ob, path, index, expr):
    fc = ob.driver_add(path, index)
    fc.driver.type = 'SCRIPTED'
    fc.driver.expression = expr
    return fc


def transport_expr(omega_per_s):
    """Angle (rad) of a part spinning with transport speed; smooth ramp up after PLAY."""
    k = omega_per_s / FPS
    f0, f1 = TRANSPORT_START, TRANSPORT_FULL
    a = f"max(min(frame,{f1})-{f0},0)"
    return f"{k:.6f}*({a}*{a}/{2 * (f1 - f0)}+max(frame-{f1},0))"


GATE = f"min(max((frame-{TRANSPORT_START})/6,0),1)"

# ---------------------------------------------------------------------------
# Geometry nodes: reusable dial tick scale
# ---------------------------------------------------------------------------
def make_dial_ticks_group():
    ng = bpy.data.node_groups.new("GN_DialTickScale", 'GeometryNodeTree')
    it = ng.interface
    it.new_socket("Geometry", in_out='INPUT', socket_type='NodeSocketGeometry')
    spec = [("Count", 'NodeSocketInt', 11), ("Radius", 'NodeSocketFloat', 0.012),
            ("Start Angle", 'NodeSocketFloat', radians(-45)), ("Sweep", 'NodeSocketFloat', radians(270)),
            ("Tick Length", 'NodeSocketFloat', 0.002), ("Tick Width", 'NodeSocketFloat', 0.0004),
            ("Ink Height", 'NodeSocketFloat', 0.00005), ("Material", 'NodeSocketMaterial', None)]
    for nm, tp, dv in spec:
        s = it.new_socket(nm, in_out='INPUT', socket_type=tp)
        if dv is not None:
            s.default_value = dv
    it.new_socket("Geometry", in_out='OUTPUT', socket_type='NodeSocketGeometry')
    N, L = ng.nodes, ng.links
    gi = N.new("NodeGroupInput")
    go = N.new("NodeGroupOutput")
    arc = N.new("GeometryNodeCurveArc")
    arc.mode = 'RADIUS'
    arc.inputs["Resolution"].default_value = 128
    L.new(gi.outputs["Radius"], arc.inputs["Radius"])
    L.new(gi.outputs["Start Angle"], arc.inputs["Start Angle"])
    L.new(gi.outputs["Sweep"], arc.inputs["Sweep Angle"])
    c2p = N.new("GeometryNodeCurveToPoints")
    c2p.mode = 'COUNT'
    L.new(arc.outputs["Curve"], c2p.inputs["Curve"])
    L.new(gi.outputs["Count"], c2p.inputs["Count"])
    cube = N.new("GeometryNodeMeshCube")
    comb_s = N.new("ShaderNodeCombineXYZ")
    L.new(gi.outputs["Tick Length"], comb_s.inputs["X"])
    L.new(gi.outputs["Tick Width"], comb_s.inputs["Y"])
    L.new(gi.outputs["Ink Height"], comb_s.inputs["Z"])
    L.new(comb_s.outputs["Vector"], cube.inputs["Size"])
    pos = N.new("GeometryNodeInputPosition")
    sep = N.new("ShaderNodeSeparateXYZ")
    L.new(pos.outputs["Position"], sep.inputs["Vector"])
    at = N.new("ShaderNodeMath")
    at.operation = 'ARCTAN2'
    L.new(sep.outputs["Y"], at.inputs[0])
    L.new(sep.outputs["X"], at.inputs[1])
    comb_r = N.new("ShaderNodeCombineXYZ")
    L.new(at.outputs[0], comb_r.inputs["Z"])
    inst = N.new("GeometryNodeInstanceOnPoints")
    L.new(c2p.outputs["Points"], inst.inputs["Points"])
    L.new(cube.outputs["Mesh"], inst.inputs["Instance"])
    try:
        L.new(comb_r.outputs["Vector"], inst.inputs["Rotation"])
    except Exception:
        e2r = N.new("FunctionNodeEulerToRotation")
        L.new(comb_r.outputs["Vector"], e2r.inputs[0])
        L.new(e2r.outputs[0], inst.inputs["Rotation"])
    tr = N.new("GeometryNodeTranslateInstances")
    comb_z = N.new("ShaderNodeCombineXYZ")
    half = N.new("ShaderNodeMath")
    half.operation = 'MULTIPLY'
    half.inputs[1].default_value = 0.5
    L.new(gi.outputs["Ink Height"], half.inputs[0])
    L.new(half.outputs[0], comb_z.inputs["Z"])
    L.new(inst.outputs["Instances"], tr.inputs["Instances"])
    L.new(comb_z.outputs["Vector"], tr.inputs["Translation"])
    tr.inputs["Local Space"].default_value = False
    real = N.new("GeometryNodeRealizeInstances")
    L.new(tr.outputs["Instances"], real.inputs[0])
    sm = N.new("GeometryNodeSetMaterial")
    L.new(real.outputs[0], sm.inputs["Geometry"])
    L.new(gi.outputs["Material"], sm.inputs["Material"])
    join = N.new("GeometryNodeJoinGeometry")
    L.new(gi.outputs["Geometry"], join.inputs[0])
    L.new(sm.outputs["Geometry"], join.inputs[0])
    L.new(join.outputs[0], go.inputs[0])
    return ng


GN_TICKS = make_dial_ticks_group()


def dial_ticks(name, loc, count, radius, start_deg, sweep_deg, length, width, mat=M_INK_W,
               coll=None, extra=None):
    """Object carrying one or more GN_DialTickScale modifiers (editable parameters)."""
    me = bpy.data.meshes.new(name)
    ob = add_obj(name, me, coll or C_MARKINGS, None, loc)
    specs = [(count, radius, start_deg, sweep_deg, length, width)] + (extra or [])
    for i, (c, r, s, sw, l, w) in enumerate(specs):
        m = ob.modifiers.new(f"Ticks_{i}", 'NODES')
        m.node_group = GN_TICKS
        ident = {it.name: it.identifier for it in GN_TICKS.interface.items_tree
                 if getattr(it, "in_out", None) == 'INPUT'}
        vals = {"Count": int(c), "Radius": float(r), "Start Angle": radians(s), "Sweep": radians(sw),
                "Tick Length": float(l), "Tick Width": float(w), "Material": mat}
        for k, v in vals.items():
            set_gn_input(m, ident[k], v)
    return ob


def set_gn_input(mod, identifier, value):
    """Blender 5.x exposes modifier inputs as mod.properties.inputs.<id>.value; 4.x used ID props."""
    props = getattr(mod, "properties", None)
    if props is not None and hasattr(props, "inputs"):
        getattr(props.inputs, identifier).value = value
    else:
        mod[identifier] = value


# ---------------------------------------------------------------------------
# Screws: one shared prototype mesh with a real cross recess (boolean applied once)
# ---------------------------------------------------------------------------
def make_screw_mesh():
    head = lathe_mesh("tmp_screw", [(0, 0), (1, 0), (1, 0.12), (0.93, 0.27), (0.72, 0.39), (0.4, 0.46), (0, 0.48)],
                      seg=32)
    ob = bpy.data.objects.new("tmp_screw", head)
    SCENE.collection.objects.link(ob)
    cutters = []
    for i, ang in enumerate((0, 90)):
        c = bpy.data.objects.new(f"tmp_slot{i}", box_mesh(f"tmp_slot{i}", 1.5, 0.17, 0.4))
        SCENE.collection.objects.link(c)
        c.location = (0, 0, 0.48)
        c.rotation_euler = (0, 0, radians(ang))
        cutters.append(c)
        m = ob.modifiers.new(f"slot{i}", 'BOOLEAN')
        m.operation = 'DIFFERENCE'
        m.object = c
        m.solver = 'EXACT'
    bpy.context.view_layer.update()
    dg = bpy.context.evaluated_depsgraph_get()
    me = bpy.data.meshes.new_from_object(ob.evaluated_get(dg))
    me.name = "MESH_Screw_PanHead_Phillips"
    for o in [ob] + cutters:
        d = o.data
        bpy.data.objects.remove(o)
        bpy.data.meshes.remove(d)
    me.shade_smooth()
    me.set_sharp_from_angle(angle=radians(40))
    me.materials.append(M_CHROME)
    return me


SCREW_MESH = make_screw_mesh()
_screw_n = [0]


def screw(loc, normal=(0, 0, 1), r=0.0018, coll=None, parent=None, twist=None):
    _screw_n[0] += 1
    ob = bpy.data.objects.new(f"HW_Screw_{_screw_n[0]:03d}", SCREW_MESH)
    (coll or C_HARDWARE).objects.link(ob)
    ob.location = loc
    q = Vector(normal).to_track_quat('Z', 'Y')
    tw = radians(twist if twist is not None else (_screw_n[0] * 37) % 90)
    ob.rotation_euler = (q.to_matrix().to_4x4() @ Matrix.Rotation(tw, 4, 'Z')).to_euler()
    ob.scale = (r, r, r)
    if parent:
        set_parent(ob, parent)
    return ob


# ---------------------------------------------------------------------------
# 1. HOUSING
# ---------------------------------------------------------------------------
OUTLINE = rrect(0, 0, W, D, R_CORNER, 10)

# boolean cutters (hidden in render, kept live so the case stays editable)
def cutter(name, me, loc=(0, 0, 0), rot=(0, 0, 0)):
    me.materials.append(M_RECESS)
    ob = add_obj(name, me, C_CUTTERS, None, loc, rot)
    ob.display_type = 'WIRE'
    ob.hide_render = True
    return ob


cutter("CUT_KeyPocket", box_mesh("CUT_KeyPocket", 0.098, 0.024, 0.024), (0, -0.138, 0.040))
cutter("CUT_CounterWindow", box_mesh("CUT_CounterWindow", 0.044, 0.024, 0.014), (-0.120, -0.138, 0.066))
cutter("CUT_VentPocket", box_mesh("CUT_VentPocket", 0.074, 0.016, 0.040), (0.115, -0.142, 0.060))
SOCKETS = [(-0.075, 0.060), (-0.045, 0.060), (-0.015, 0.060)]
for i, (sy, sz) in enumerate(SOCKETS):
    me = lathe_mesh(f"CUT_Socket{i}", [(0, 0), (0.0075, 0), (0.0075, 0.016), (0, 0.016)], seg=48)
    cutter(f"CUT_Socket{i}", me, (0.174, sy, sz), (0, radians(90), 0))
# engraved battery-door seam on the left side
_door_o = rrect(0, 0, 0.050, 0.120, 0.004, 6)
_door_i = rrect(0, 0, 0.0484, 0.1184, 0.0032, 6)
cutter("CUT_BatteryDoorSeam", profile_mesh("CUT_BatteryDoorSeam", [_door_o, _door_i], -0.004, 0.0012, smooth=False),
       (-0.180, -0.005, 0.060), (0, radians(-90), 0))

case_upper = add_obj("Case_Upper_Shell", profile_mesh("Case_Upper_Shell", [OUTLINE], Z_SEAM + 0.0005, Z_BODY_TOP),
                     C_HOUSING, M_CASE)
mb = case_upper.modifiers.new("Boolean_Recesses", 'BOOLEAN')
mb.operation = 'DIFFERENCE'
mb.operand_type = 'COLLECTION'
mb.collection = C_CUTTERS
mb.solver = 'EXACT'
try:
    mb.material_mode = 'TRANSFER'
except Exception:
    pass
bevel(case_upper, 0.0022, 3)

case_lower = add_obj("Case_Lower_Bumper", profile_mesh("Case_Lower_Bumper", [rrect(0, 0, W + 0.002, D + 0.002, R_CORNER + 0.001, 10)],
                                                       Z_FEET, Z_SEAM), C_HOUSING, M_BLACK_ANOD)
bevel(case_lower, 0.0025, 3)

# rubber feet
FOOT = lathe_mesh("MESH_RubberFoot", [(0, 0), (0.0085, 0), (0.0095, 0.002), (0.0095, 0.008), (0.0086, 0.0112),
                                      (0.006, 0.0121), (0, 0.0121)], seg=48)
FOOT.materials.append(M_RUBBER)
for i, (fx, fy) in enumerate([(-0.150, -0.110), (0.150, -0.110), (-0.150, 0.110), (0.150, 0.110)]):
    add_obj(f"Foot_Rubber_{i}", FOOT, C_HOUSING, None, (fx, fy, 0.0))

# front face screws
for sx in (-0.166, 0.166):
    for sz in (0.034, 0.092):
        screw((sx, -W / 2 * 0 - D / 2 - 0.0002, sz), (0, -1, 0), 0.0019)

# front louvre ventilation (array modifier, cut pocket behind)
slat_bm = bmesh.new()
bmesh.ops.create_cube(slat_bm, size=1.0)
for v in slat_bm.verts:
    v.co = Vector((v.co.x * 0.0725, v.co.y * 0.0055, v.co.z * 0.0011))
bmesh.ops.rotate(slat_bm, verts=slat_bm.verts, cent=(0, 0, 0), matrix=Matrix.Rotation(radians(-35), 3, 'X'))
slat_me = bpy.data.meshes.new("Vent_Louvre_Slat")
slat_bm.to_mesh(slat_me)
slat_bm.free()
slat_me.shade_smooth()
slat_me.set_sharp_from_angle(angle=radians(35))
slat = add_obj("Vent_Louvre_Array", slat_me, C_HOUSING, M_CASE, (0.115, -0.1373, 0.0438))
arr = slat.modifiers.new("Array_Louvres", 'ARRAY')
arr.count = 9
arr.use_relative_offset = False
arr.use_constant_offset = True
arr.constant_offset_displace = (0, 0, 0.0040)
bevel(slat, 0.0003, 2)

# mechanical tape counter (front left)
add_obj("Counter_Window_Glass", box_mesh("Counter_Window_Glass", 0.0436, 0.0006, 0.0136), C_HOUSING, M_GLASS,
        (-0.120, -0.1389, 0.066))
counter_digits = "0247"
COUNTER_WHEEL = lathe_mesh("MESH_CounterWheel", [(0, -0.0037), (0.0045, -0.0037), (0.0045, 0.0037), (0, 0.0037)], seg=40)
COUNTER_WHEEL.materials.append(M_BAKELITE)
for i, ch in enumerate(counter_digits):
    x = -0.1335 + i * 0.009
    wpiv = empty(f"RIG_CounterWheel_{i}", (x, -0.133, 0.066), size=0.006)
    add_obj(f"Counter_Wheel_{i}", COUNTER_WHEEL, C_HOUSING, None, (x, -0.133, 0.066), (0, radians(90), 0), parent=wpiv)
    text(f"TXT_CounterDigit_{i}", ch, 0.0058, (x, -0.13762, 0.066), ROT_FRONT, M_INK_W, C_HOUSING, parent=wpiv)
    if i == 3:
        drive(wpiv, "rotation_euler", 0, transport_expr(TAPE_SPEED / PACK_TAKEUP) + "*0.25")
btn = lathe_mesh("Counter_Reset_Button", [(0, 0), (0.0042, 0), (0.0042, 0.0008), (0.0030, 0.0010), (0.0030, 0.0032),
                                          (0.0026, 0.0038), (0, 0.0039)], seg=40)
add_obj("Counter_Reset_Button", btn, C_CONTROLS, M_CHROME, (-0.088, -0.140, 0.066), ROT_FRONT)
text("TXT_Counter", "COUNTER", 0.0026, (-0.120, -0.1401, 0.0545), ROT_FRONT, M_INK_W, C_MARKINGS, spacing=1.15)
text("TXT_Reset", "RESET", 0.0022, (-0.088, -0.1401, 0.0585), ROT_FRONT, M_INK_W, C_MARKINGS)

# front badge
badge = add_obj("Badge_Nameplate", profile_mesh("Badge_Nameplate", [rrect(0, 0, 0.056, 0.016, 0.002, 4)], 0, 0.0010),
                C_HOUSING, M_ALU, (-0.112, -0.1400, 0.036), ROT_FRONT)
bevel(badge, 0.0003, 2)
text("TXT_Badge_Brand", "STRATON", 0.0072, (-0.1205, -0.14105, 0.0362), ROT_FRONT, M_INK_K, C_MARKINGS, spacing=1.25)
text("TXT_Badge_Model", "FR-74", 0.0034, (-0.0950, -0.14105, 0.0362), ROT_FRONT, M_INK_R, C_MARKINGS)
for bx in (-0.1375, -0.0865):
    screw((bx, -0.1412, 0.036), (0, -1, 0), 0.0011)

# right side: DIN connector sockets
SHELL = lathe_mesh("MESH_DIN_Shell", [(0.0062, 0), (0.0075, 0), (0.0075, 0.0055), (0.0071, 0.0060), (0.0062, 0.0060)],
                   seg=48, closed=True)
SHELL.materials.append(M_CHROME)
INSUL = lathe_mesh("MESH_DIN_Insulator", [(0, 0), (0.0064, 0), (0.0064, 0.002), (0, 0.002)], seg=48)
INSUL.materials.append(M_BAKELITE)
pins = []
for k in range(5):
    a = radians(180 + 45 * k)
    pins.append(circle(0.0035 * cos(a), 0.0035 * sin(a), 0.0006, 12))
pins.append(rrect(0, 0.0047, 0.0016, 0.0012, 0.0003, 2))
PINS = flat_mesh("MESH_DIN_PinHoles", pins, 0.00004)
PINS.materials.append(M_RECESS)
for i, ((sy, sz), lab) in enumerate(zip(SOCKETS, ("MIC", "LINE", "PHONES"))):
    add_obj(f"DIN_Socket_Shell_{i}", SHELL, C_HOUSING, None, (0.1742, sy, sz), (0, radians(90), 0))
    add_obj(f"DIN_Socket_Insulator_{i}", INSUL, C_HOUSING, None, (0.1755, sy, sz), (0, radians(90), 0))
    add_obj(f"DIN_Socket_Pins_{i}", PINS, C_HOUSING, None, (0.1775, sy, sz), (0, radians(90), radians(0)))
    text(f"TXT_Socket_{lab}", lab, 0.0030, (W / 2 + 0.0001, sy, sz + 0.0125), ROT_RIGHT, M_INK_W, C_MARKINGS,
         spacing=1.1)
text("TXT_Side_Inputs", "INPUT / OUTPUT  200 mV - 2 V", 0.0024, (W / 2 + 0.0001, -0.045, 0.043), ROT_RIGHT,
     M_INK_W, C_MARKINGS)
# left side battery door screws (coin slot)
for dy in (-0.050, 0.040):
    screw((-W / 2 - 0.0002, dy - 0.005, 0.060), (-1, 0, 0), 0.0032, twist=0)
text("TXT_Battery", "BATTERY  6 x 1.5 V  R20", 0.0030, (-W / 2 - 0.0001, -0.005, 0.0435), ROT_LEFT, M_INK_W,
     C_MARKINGS)


# strap lugs with D-rings (both sides)
def strap_lug(side):
    sx = side * W / 2
    blk = add_obj(f"StrapLug_Block_{'R' if side > 0 else 'L'}",
                  profile_mesh("StrapLug_Block", [rrect(0, 0, 0.016, 0.026, 0.004, 5)], 0, 0.0045),
                  C_HOUSING, M_CHROME, (sx, 0.085, 0.081), (0, radians(90 * side), 0))
    bevel(blk, 0.0009, 3)
    for dy in (-0.008, 0.008):
        screw((sx + side * 0.0047, 0.085 + dy, 0.081), (side, 0, 0), 0.0013)
    cu = bpy.data.curves.new(f"StrapLug_Ring_{'R' if side > 0 else 'L'}", 'CURVE')
    cu.dimensions = '3D'
    cu.bevel_depth = 0.0016
    cu.bevel_resolution = 4
    sp = cu.splines.new('POLY')
    pts = [(p[0], p[1]) for p in rrect(0, 0, 0.022, 0.014, 0.005, 6)]
    sp.points.add(len(pts) - 1)
    for p, (u, v) in zip(sp.points, pts):
        p.co = (sx + side * 0.0028, 0.085 + u, 0.0745 + v, 1)
    sp.use_cyclic_u = True
    cu.materials.append(M_CHROME)
    add_obj(cu.name, cu, C_HOUSING)


strap_lug(1)
strap_lug(-1)

# hinge: body leaf + knuckle array (array modifier)
leaf_b = add_obj("Hinge_Leaf_Body", box_mesh("Hinge_Leaf_Body", 0.30, 0.0012, 0.010), C_HOUSING, M_CHROME,
                 (0, D / 2 + 0.0006, 0.0955))
bevel(leaf_b, 0.0003, 2)
for hx in (-0.12, -0.04, 0.04, 0.12):
    screw((hx, D / 2 + 0.0013, 0.0955), (0, 1, 0), 0.0011)
knuckle = lathe_mesh("Hinge_Knuckle", [(0, 0), (0.0026, 0), (0.0026, 0.0175), (0, 0.0175)], seg=32)
kn = add_obj("Hinge_Knuckles", knuckle, C_HOUSING, M_CHROME, (-0.150, HINGE.y, HINGE.z), (0, radians(90), 0))
ar = kn.modifiers.new("Array_Knuckles", 'ARRAY')
ar.count = 17
ar.use_relative_offset = False
ar.use_constant_offset = True
ar.constant_offset_displace = (0, 0, 0.01775)
bevel(kn, 0.0004, 2)

# ---------------------------------------------------------------------------
# 2. DECK PLATE + CONTROL PLATE (with real apertures for the meters)
# ---------------------------------------------------------------------------
VU_CENTERS = [Vector((-0.130, -0.088, 0)), Vector((-0.076, -0.088, 0))]
VU_W, VU_H = 0.046, 0.032
apertures = [rrect(c.x, c.y, VU_W, VU_H, 0.0025, 4) for c in VU_CENTERS]
deck = add_obj("Deck_Plate", profile_mesh("Deck_Plate", [rrect(0, 0, W - 0.008, D - 0.008, R_CORNER - 0.004, 10)]
                                          + apertures, Z_BODY_TOP, Z_DECK), C_DECK, M_ALU)
bevel(deck, 0.0008, 3)
ctrl = add_obj("Control_Plate", profile_mesh("Control_Plate", [rrect(0, -0.092, 0.336, 0.072, 0.004, 6)] + apertures,
                                             Z_DECK, Z_CTRL), C_CONTROLS, M_BLACK_ANOD)
bevel(ctrl, 0.0005, 2)
for sx, sy in [(-0.162, 0.126), (0.162, 0.126), (0, 0.126), (-0.162, -0.010), (0.162, -0.010)]:
    screw((sx, sy, Z_DECK), (0, 0, 1), 0.0019)
for sx, sy in [(-0.163, -0.061), (0.163, -0.061), (-0.163, -0.123), (0.163, -0.123)]:
    screw((sx, sy, Z_CTRL), (0, 0, 1), 0.0015)

# ---------------------------------------------------------------------------
# 3. VU METERS (liner, face card, scales, needle, bezel, acrylic lens)
# ---------------------------------------------------------------------------
def vu_angle(db):
    p = 10 ** (db / 20.0) / 10 ** (3 / 20.0)
    return radians(135 - 90 * p)


def build_vu(idx, c, label):
    tag = f"VU_{label}"
    liner = add_obj(f"{tag}_Liner", profile_mesh(f"{tag}_Liner",
                    [rrect(c.x, c.y, VU_W - 0.0002, VU_H - 0.0002, 0.0024, 4),
                     rrect(c.x, c.y, VU_W - 0.0022, VU_H - 0.0022, 0.0016, 4)], Z_BODY_TOP, Z_CTRL - 0.0001),
                    C_METERS, M_BAKELITE)
    zf = Z_BODY_TOP + 0.0004
    face = add_obj(f"{tag}_FaceCard", profile_mesh(f"{tag}_FaceCard", [rrect(c.x, c.y, VU_W - 0.0024, VU_H - 0.0024,
                                                                             0.0015, 4)], Z_BODY_TOP, zf),
                   C_METERS, M_VU)
    px, py = c.x, c.y - 0.0115
    zi = zf + 0.00001
    # main dB scale: black band to 0 VU, heavier red band above
    k_polys = [arc_band(px, py, 0.0170, 0.01735, vu_angle(0), vu_angle(-20), 40)]
    r_polys = [arc_band(px, py, 0.0170, 0.0183, vu_angle(3), vu_angle(0), 16)]
    for db in (-20, -10, -7, -5, -3, -2, -1, 0, 1, 2, 3):
        a = vu_angle(db)
        l = 0.0028 if db in (-20, -10, -5, 0, 3) else 0.0020
        w = 0.00028
        t = Vector((-sin(a), cos(a))) * w / 2
        p0 = Vector((px + 0.0170 * cos(a), py + 0.0170 * sin(a)))
        p1 = Vector((px + (0.0170 + l) * cos(a), py + (0.0170 + l) * sin(a)))
        quad = [tuple(p0 - t), tuple(p1 - t), tuple(p1 + t), tuple(p0 + t)]
        (r_polys if db >= 0 else k_polys).append(quad)
        txt = str(abs(db))
        tr = 0.0218
        text(f"TXT_{tag}_dB_{db}", txt, 0.0019, (px + tr * cos(a), py + tr * sin(a), zi), (0, 0, a - pi / 2),
             M_INK_R if db >= 0 else M_INK_K, C_METERS)
    mk = add_obj(f"{tag}_Scale_Black", flat_mesh(f"{tag}_Scale_Black", k_polys), C_METERS, M_INK_K, (0, 0, zi))
    mr = add_obj(f"{tag}_Scale_Red", flat_mesh(f"{tag}_Scale_Red", r_polys), C_METERS, M_INK_R, (0, 0, zi))
    # linear percentage scale (geometry nodes)
    dial_ticks(f"{tag}_Scale_Percent", (px, py, zi), 11, 0.0148, 45, 90, 0.0011, 0.00018, M_INK_K, C_METERS,
               extra=[(3, 0.0150, 45, 90, 0.0017, 0.00024)])
    text(f"TXT_{tag}_Minus", "-", 0.0026, (px - 0.0205, py + 0.0080, zi), (0, 0, 0), M_INK_K, C_METERS)
    text(f"TXT_{tag}_Plus", "+", 0.0024, (px + 0.0205, py + 0.0080, zi), (0, 0, 0), M_INK_R, C_METERS)
    text(f"TXT_{tag}_VU", "VU", 0.0046, (px, py + 0.0080, zi), (0, 0, 0), M_INK_K, C_METERS, spacing=1.1)
    text(f"TXT_{tag}_Ch", label, 0.0030, (c.x + 0.0170, c.y - 0.0110, zi), (0, 0, 0), M_INK_K, C_METERS)
    text(f"TXT_{tag}_Pct", "0      %      100", 0.0012, (px, py + 0.0118, zi), (0, 0, 0), M_INK_K, C_METERS)
    # needle on a pivot (driven by a damped program signal once the transport runs)
    piv = empty(f"RIG_{tag}_NeedlePivot", (px, py, zf), size=0.004)
    needle_poly = [(-0.00030, 0.0), (0.00030, 0.0), (0.00009, 0.0212), (-0.00009, 0.0212)]
    nd = add_obj(f"{tag}_Needle", flat_mesh(f"{tag}_Needle", [needle_poly], 0.00012), C_METERS, M_INK_K,
                 (px, py, zf + 0.0009), parent=piv)
    cap = lathe_mesh(f"{tag}_PivotCap", [(0, 0), (0.0016, 0), (0.0016, 0.0010), (0.0012, 0.0014), (0, 0.0014)], seg=24)
    add_obj(f"{tag}_PivotCap", cap, C_METERS, M_BAKELITE, (px, py, zf), parent=piv)
    ph = 0.9 * idx
    drive(piv, "rotation_euler", 2,
          f"0.873-(1.08+0.30*sin(frame*0.61+{ph:.2f})+0.16*sin(frame*1.73+{ph * 2:.2f}))*{GATE}")
    # bezel and acrylic lens
    bz = add_obj(f"{tag}_Bezel", profile_mesh(f"{tag}_Bezel", [rrect(c.x, c.y, VU_W + 0.007, VU_H + 0.007, 0.005, 6),
                                                               rrect(c.x, c.y, VU_W - 0.0024, VU_H - 0.0024, 0.0016, 4)],
                                              Z_CTRL, Z_CTRL + 0.0022), C_CONTROLS, M_CHROME)
    bevel(bz, 0.0006, 3)
    add_obj(f"{tag}_Lens", profile_mesh(f"{tag}_Lens", [rrect(c.x, c.y, VU_W - 0.0025, VU_H - 0.0025, 0.0016, 4)],
                                        Z_CTRL + 0.0004, Z_CTRL + 0.0016), C_CONTROLS, M_GLASS)
    for sx in (-1, 1):
        screw((c.x + sx * (VU_W / 2 + 0.0016), c.y, Z_CTRL + 0.0022), (0, 0, 1), 0.0009)


build_vu(0, VU_CENTERS[0], "L")
build_vu(1, VU_CENTERS[1], "R")
text("TXT_VU_Title", "MODULATION  dB", 0.0026, (-0.103, -0.1155, Z_CTRL + 0.00004), mat=M_INK_W, spacing=1.15)

# record pilot lamp
lamp_bz = lathe_mesh("Lamp_Bezel", [(0.0018, 0), (0.0034, 0), (0.0034, 0.0012), (0.0026, 0.0018), (0.0018, 0.0018)],
                     seg=32, closed=True)
add_obj("Lamp_Bezel", lamp_bz, C_CONTROLS, M_CHROME, (-0.040, -0.066, Z_CTRL))
lamp = lathe_mesh("Lamp_Jewel", [(0, 0), (0.0021, 0), (0.0021, 0.0012)] +
                  [(0.0021 * cos(radians(a)), 0.0012 + 0.0016 * sin(radians(a))) for a in range(15, 91, 15)], seg=32)
add_obj("Lamp_Jewel_Record", lamp, C_CONTROLS, M_LAMP, (-0.040, -0.066, Z_CTRL))
text("TXT_Lamp", "REC", 0.0024, (-0.040, -0.0715, Z_CTRL + 0.00004), mat=M_INK_W)


# ---------------------------------------------------------------------------
# 4. ROTARY CONTROLS AND TOGGLES
# ---------------------------------------------------------------------------
def skirt_knob(name, x, y, r=0.0085, value_deg=0.0, z0=Z_CTRL):
    """Knurled bakelite knob with skirt, spun aluminium insert and white pointer."""
    piv = empty(f"RIG_{name}", (x, y, z0), size=0.006)
    nut = lathe_mesh(f"{name}_Nut", [(0, 0), (0.0048, 0), (0.0048, 0.0010), (0, 0.0010)], seg=6)
    add_obj(f"{name}_Nut", nut, C_CONTROLS, M_CHROME, (x, y, z0), (0, 0, radians(15)))
    zb = z0 + 0.0011
    prof = [(0, zb), (r, zb), (r, zb + 0.0014), (r * 0.86, zb + 0.0020), (r * 0.82, zb + 0.0030),
            (r * 0.80, zb + 0.0100), (r * 0.74, zb + 0.0110), (r * 0.66, zb + 0.0113), (0, zb + 0.0113)]
    kme = lathe_mesh(f"{name}_Body", prof, seg=180, knurl=(30, 0.00045, zb + 0.0029, zb + 0.0101))
    kb = add_obj(f"{name}_Body", kme, C_CONTROLS, M_BAKELITE, (x, y, 0), parent=piv)
    ins = lathe_mesh(f"{name}_Insert", [(0, 0), (r * 0.62, 0), (r * 0.62, 0.0004), (r * 0.3, 0.0003), (0, 0.0003)], seg=64)
    add_obj(f"{name}_Insert", ins, C_CONTROLS, M_SPUN, (x, y, zb + 0.0113), parent=piv)
    pl = flat_mesh(f"{name}_PointerLine", [rrect(0, r * 0.93, 0.0006, r * 0.14, 0.0001, 1),
                                           rrect(0, r * 0.40, 0.0004, r * 0.36, 0.0001, 1)])
    p1 = add_obj(f"{name}_Pointer", pl, C_CONTROLS, M_INK_W, (x, y, zb + 0.0014), parent=piv)
    # second line on the insert, same mesh lifted to the insert top
    add_obj(f"{name}_PointerTop", pl, C_CONTROLS, M_INK_K, (x, y, zb + 0.01165), parent=piv)
    piv.rotation_euler.z = radians(value_deg)
    return piv


def chicken_head_knob(name, x, y, value_deg=0.0, z0=Z_CTRL):
    piv = empty(f"RIG_{name}", (x, y, z0), size=0.006)
    nut = lathe_mesh(f"{name}_Nut", [(0, 0), (0.0048, 0), (0.0048, 0.0010), (0, 0.0010)], seg=6)
    add_obj(f"{name}_Nut", nut, C_CONTROLS, M_CHROME, (x, y, z0))
    zb = z0 + 0.0011
    base = lathe_mesh(f"{name}_Base", [(0, 0), (0.0080, 0), (0.0080, 0.0012), (0.0068, 0.0040), (0, 0.0040)], seg=96)
    add_obj(f"{name}_Base", base, C_CONTROLS, M_BAKELITE, (x, y, zb), parent=piv)
    bar = [(-0.0028, -0.0075), (0.0028, -0.0075), (0.0040, 0.0010), (0.0012, 0.0118), (-0.0012, 0.0118),
           (-0.0040, 0.0010)]
    bar = smooth_poly(bar, 2)
    bo = add_obj(f"{name}_Bar", profile_mesh(f"{name}_Bar", [bar], 0.0020, 0.0095), C_CONTROLS, M_BAKELITE,
                 (x, y, zb), parent=piv)
    bevel(bo, 0.0012, 3, angle=40)
    add_obj(f"{name}_Pointer", flat_mesh(f"{name}_Pointer", [rrect(0, 0.0072, 0.0007, 0.0070, 0.0002, 1)]),
            C_CONTROLS, M_INK_W, (x, y, zb + 0.00951), parent=piv)
    piv.rotation_euler.z = radians(value_deg)
    return piv


def toggle(name, x, y, up=True, z0=Z_CTRL):
    nut = lathe_mesh(f"{name}_Nut", [(0, 0), (0.0046, 0), (0.0046, 0.0014), (0, 0.0014)], seg=6)
    add_obj(f"{name}_HexNut", nut, C_CONTROLS, M_CHROME, (x, y, z0))
    bush = lathe_mesh(f"{name}_Bushing", [(0, 0), (0.0030, 0), (0.0030, 0.0040), (0.0026, 0.0044), (0, 0.0044)],
                      seg=40)
    add_obj(f"{name}_Bushing", bush, C_CONTROLS, M_CHROME, (x, y, z0 + 0.0014))
    piv = empty(f"RIG_{name}", (x, y, z0 + 0.0050), size=0.004)
    lev = lathe_mesh(f"{name}_Bat", [(0, -0.0015), (0.0017, -0.0015), (0.0013, 0.0100)] +
                     [(0.0021 * cos(radians(a)), 0.0112 + 0.0021 * sin(radians(a))) for a in range(-60, 91, 15)],
                     seg=32)
    add_obj(f"{name}_Bat", lev, C_CONTROLS, M_CHROME, (x, y, z0 + 0.0050), parent=piv)
    piv.rotation_euler.x = radians(-20 if up else 20)
    return piv


KNOB_Y = -0.090
KX = [-0.010, 0.027, 0.064, 0.098]
z_ink = Z_CTRL + 0.00002
# 1+2: input level knobs with 0-10 scales
for i, (kx, lab, val) in enumerate(zip(KX[:2], ("INPUT  L", "INPUT  R"), (6.5, 6.0))):
    ang = 225 - 27 * val
    skirt_knob(f"Knob_Input_{'LR'[i]}", kx, KNOB_Y, value_deg=ang - 90)
    dial_ticks(f"SCL_Input_{'LR'[i]}", (kx, KNOB_Y, z_ink), 21, 0.0118, -45, 270, 0.0013, 0.00025,
               extra=[(11, 0.0122, -45, 270, 0.0022, 0.00045)])
    for v in range(0, 11, 2):
        a = radians(225 - 27 * v)
        text(f"TXT_Input_{'LR'[i]}_{v}", str(v), 0.0022, (kx + 0.0157 * cos(a), KNOB_Y + 0.0157 * sin(a), z_ink))
    text(f"TXT_Input_{'LR'[i]}_Label", lab, 0.0026, (kx, KNOB_Y - 0.0255, z_ink), spacing=1.1)
# 3: monitor selector
chicken_head_knob("Knob_Monitor", KX[2], KNOB_Y, value_deg=45)
dial_ticks("SCL_Monitor", (KX[2], KNOB_Y, z_ink), 3, 0.0120, 45, 90, 0.0022, 0.00045)
for a, lab in ((135, "DIR"), (90, "TAPE"), (45, "BATT")):
    text(f"TXT_Monitor_{lab}", lab, 0.0021,
         (KX[2] + 0.0158 * cos(radians(a)), KNOB_Y + 0.0158 * sin(radians(a)), z_ink), (0, 0, radians(a - 90)))
text("TXT_Monitor_Label", "MONITOR", 0.0026, (KX[2], KNOB_Y - 0.0255, z_ink), spacing=1.1)
# 4: tape speed / equalisation selector
skirt_knob("Knob_Speed", KX[3], KNOB_Y, r=0.0075, value_deg=30)
dial_ticks("SCL_Speed", (KX[3], KNOB_Y, z_ink), 2, 0.0110, 60, 60, 0.0022, 0.00045)
for a, lab in ((120, "9.5"), (60, "19")):
    text(f"TXT_Speed_{lab}", lab, 0.0024,
         (KX[3] + 0.0148 * cos(radians(a)), KNOB_Y + 0.0148 * sin(radians(a)), z_ink))
text("TXT_Speed_Unit", "cm/s", 0.0020, (KX[3], KNOB_Y + 0.0175, z_ink))
text("TXT_Speed_Label", "SPEED / EQ", 0.0026, (KX[3], KNOB_Y - 0.0255, z_ink), spacing=1.1)
# 5+6: toggles
for tx, nm, up in ((0.131, "LIMITER", True), (0.155, "SOURCE", False)):
    toggle(f"Toggle_{nm.title()}", tx, KNOB_Y + 0.002, up)
    top, bot = ("ON", "OFF") if nm == "LIMITER" else ("MIC", "LINE")
    text(f"TXT_{nm}_Up", top, 0.0021, (tx, KNOB_Y + 0.0145, z_ink))
    text(f"TXT_{nm}_Dn", bot, 0.0021, (tx, KNOB_Y - 0.0105, z_ink))
    text(f"TXT_{nm}_Label", nm, 0.0024, (tx, KNOB_Y - 0.0255, z_ink), spacing=1.05)
# model marking line on the control plate
text("TXT_ModelLine", "STRATON  FR-74  REPORTER   -   PORTABLE MAGNETIC TAPE RECORDER", 0.0026,
     (0.058, -0.0625, z_ink), spacing=1.12)
text("TXT_Serial", "No. 74-03118", 0.0020, (-0.150, -0.0625, z_ink), align='LEFT')


# ---------------------------------------------------------------------------
# 5. PIANO-KEY TRANSPORT CONTROLS (front face)
# ---------------------------------------------------------------------------
def tri(cx, cy, s, d=1):
    return [(cx - d * s * 0.45, cy - s * 0.55), (cx + d * s * 0.55, cy), (cx - d * s * 0.45, cy + s * 0.55)]


KEYS = [("REW", lambda: [tri(-0.0018, 0, 0.004, -1), tri(0.0022, 0, 0.004, -1)]),
        ("PLAY", lambda: [tri(0, 0, 0.0048, 1)]),
        ("STOP", lambda: [rrect(0, 0, 0.0042, 0.0042, 0.0003, 2)]),
        ("FF", lambda: [tri(-0.0022, 0, 0.004, 1), tri(0.0018, 0, 0.004, 1)]),
        ("REC", lambda: [circle(0, 0, 0.0024, 32)])]
KEY_RIGS = {}
for i, (nm, sym) in enumerate(KEYS):
    kx = -0.0384 + i * 0.0192
    rig = empty(f"RIG_Key_{nm}", (kx, -0.1378, 0.040), size=0.006)
    kb = add_obj(f"Key_{nm}", box_mesh(f"Key_{nm}", 0.0175, 0.0165, 0.022), C_CONTROLS,
                 M_RED if nm == "REC" else M_BAKELITE, (kx, -0.1378, 0.040), parent=rig)
    bevel(kb, 0.0014, 4)
    cap = add_obj(f"Key_{nm}_FacePlate", profile_mesh(f"Key_{nm}_Face", [rrect(0, 0, 0.0145, 0.019, 0.0012, 3)], 0, 0.0004),
                  C_CONTROLS, M_ALU if nm != "REC" else M_RED, (kx, -0.1460, 0.040), ROT_FRONT, parent=rig)
    add_obj(f"Key_{nm}_Symbol", flat_mesh(f"Key_{nm}_Symbol", sym()), C_CONTROLS,
            M_INK_W if nm == "REC" else M_INK_K, (kx, -0.14641, 0.0425), ROT_FRONT, parent=rig)
    text(f"TXT_Key_{nm}", nm, 0.0028, (kx, -0.1401, 0.0560), ROT_FRONT, M_INK_W, C_MARKINGS, spacing=1.05)
    KEY_RIGS[nm] = rig

# ---------------------------------------------------------------------------
# 6. LATCH (body hasp + lid keeper)
# ---------------------------------------------------------------------------
lb = add_obj("Latch_Base", profile_mesh("Latch_Base", [rrect(0, 0, 0.026, 0.013, 0.002, 4)], 0, 0.0025), C_HARDWARE,
             M_CHROME, (0, -D / 2, 0.0860), ROT_FRONT)
bevel(lb, 0.0006, 3)
for sx in (-0.0095, 0.0095):
    screw((sx, -D / 2 - 0.0026, 0.0860), (0, -1, 0), 0.0012)
LATCH_PIV = Vector((0, -0.1440, 0.0880))
kn2 = lathe_mesh("Latch_Knuckle", [(0, -0.010), (0.0021, -0.010), (0.0021, 0.010), (0, 0.010)], seg=32)
add_obj("Latch_Knuckle", kn2, C_HARDWARE, M_CHROME, LATCH_PIV, (0, radians(90), 0))
latch_rig = empty("RIG_Latch_Hasp", LATCH_PIV, size=0.01)
hasp = add_obj("Latch_Hasp", box_mesh("Latch_Hasp", 0.020, 0.0012, 0.026), C_HARDWARE, M_CHROME,
               (0, LATCH_PIV.y - 0.0016, LATCH_PIV.z + 0.0130), parent=latch_rig)
bevel(hasp, 0.0004, 2)
lip = add_obj("Latch_Hasp_Lip", box_mesh("Latch_Hasp_Lip", 0.020, 0.0052, 0.0014), C_HARDWARE, M_CHROME,
              (0, LATCH_PIV.y - 0.0022 + 0.0026, LATCH_PIV.z + 0.0253), parent=latch_rig)
bevel(lip, 0.0004, 2)

# ---------------------------------------------------------------------------
# 7. TRANSPORT: heads, guides, capstan, pinch roller
# ---------------------------------------------------------------------------
hp = add_obj("Head_Mount_Plate", profile_mesh("Head_Mount_Plate", [rrect(-0.014, -0.018, 0.088, 0.018, 0.003, 4)],
                                             Z_DECK, Z_DECK + 0.0025), C_TRANSPORT, M_BLACK_ANOD)
bevel(hp, 0.0005, 2)
for sx in (-0.054, 0.026):
    screw((sx, -0.013, Z_DECK + 0.0025), (0, 0, 1), 0.0013)

HEADS = [("Erase", -0.030), ("Record", -0.010), ("Playback", 0.012)]
yf = Y_TAPE + TAPE_T / 2 + 0.00005
for nm, hx in HEADS:
    ac = Vector((hx, yf + 0.012))
    pts = [(ac.x + 0.012 * cos(radians(a)), ac.y + 0.012 * sin(radians(a))) for a in range(245, 296, 2)]
    pts += [(hx + 0.0051, -0.017), (hx - 0.0051, -0.017)]
    zb = Z_DECK + 0.0025
    blk = add_obj(f"Head_{nm}_Base", profile_mesh(f"Head_{nm}_Base", [rrect(hx, -0.0225, 0.012, 0.012, 0.001, 2)],
                                                  zb, zb + 0.0020), C_TRANSPORT, M_BAKELITE)
    hd = add_obj(f"Head_{nm}", profile_mesh(f"Head_{nm}", [pts], zb + 0.0020, zb + 0.0170), C_TRANSPORT, M_HEAD)
    bevel(hd, 0.0004, 3)
    gap = add_obj(f"Head_{nm}_Gap", box_mesh(f"Head_{nm}_Gap", 0.00012, 0.00004, 0.0055), C_TRANSPORT, M_INK_K,
                  (hx, yf - 0.00001, Z_TAPE))
    sh = add_obj(f"Head_{nm}_Shield", box_mesh(f"Head_{nm}_Shield", 0.0104, 0.004, 0.0150), C_TRANSPORT, M_CHROME,
                 (hx, -0.0190, zb + 0.0095))
    bevel(sh, 0.0006, 2)
    text(f"TXT_Head_{nm}", {"Erase": "ERASE", "Record": "REC", "Playback": "PLAY"}[nm], 0.0024,
         (hx, -0.0418, Z_DECK + 0.00003), mat=M_INK_K)
hood = add_obj("Head_Hood", profile_mesh("Head_Hood", [rrect(-0.010, -0.0215, 0.058, 0.018, 0.003, 4)],
                                        Z_DECK + 0.0198, Z_DECK + 0.0226), C_TRANSPORT, M_BLACK_ANOD)
bevel(hood, 0.0007, 3)
for sx in (-0.036, 0.016):
    add_obj(f"Head_Hood_Post_{sx:+.3f}", lathe_mesh("Hood_Post", [(0, 0), (0.0014, 0), (0.0014, 0.0173), (0, 0.0173)],
                                                     seg=24), C_TRANSPORT, M_CHROME, (sx, -0.0145, Z_DECK + 0.0025))
    screw((sx, -0.0145, Z_DECK + 0.0226), (0, 0, 1), 0.0012)
text("TXT_Hood", "STRATON", 0.0030, (-0.010, -0.0222, Z_DECK + 0.02263), mat=M_INK_W, spacing=1.2)

# fixed tape guides flanking the head stack
for i, gx in enumerate((-0.048, 0.026)):
    gy = Y_TAPE + TAPE_T / 2 + 0.00005 + 0.002
    prof = [(0, 0), (0.0035, 0), (0.0035, 0.0010), (0.0020, 0.0012), (0.0020, Z_TAPE - TAPE_W / 2 - 0.0007 - Z_DECK - 0.0025),
            (0.0032, Z_TAPE - TAPE_W / 2 - 0.0007 - Z_DECK - 0.0025), (0.0032, Z_TAPE - TAPE_W / 2 - 0.0002 - Z_DECK - 0.0025),
            (0.0020, Z_TAPE - TAPE_W / 2 - 0.0002 - Z_DECK - 0.0025),
            (0.0020, Z_TAPE + TAPE_W / 2 + 0.0002 - Z_DECK - 0.0025),
            (0.0032, Z_TAPE + TAPE_W / 2 + 0.0002 - Z_DECK - 0.0025),
            (0.0032, Z_TAPE + TAPE_W / 2 + 0.0008 - Z_DECK - 0.0025), (0.0016, Z_TAPE + TAPE_W / 2 + 0.0012 - Z_DECK - 0.0025),
            (0, Z_TAPE + TAPE_W / 2 + 0.0012 - Z_DECK - 0.0025)]
    add_obj(f"Guide_Fixed_{i}", lathe_mesh(f"Guide_Fixed_{i}", prof, seg=40), C_TRANSPORT, M_CHROME,
            (gx, gy, Z_DECK + 0.0025))


def guide_roller(name, c):
    post = lathe_mesh(f"{name}_Post", [(0, 0), (0.0052, 0), (0.0052, 0.0010), (0.0024, 0.0013), (0.0022, 0.0162),
                                        (0, 0.0162)], seg=40)
    add_obj(f"{name}_Post", post, C_TRANSPORT, M_CHROME, (c.x, c.y, Z_DECK))
    rig = empty(f"RIG_{name}", (c.x, c.y, Z_DECK), size=0.008)
    z0 = Z_TAPE - TAPE_W / 2 - 0.0012
    z1 = Z_TAPE + TAPE_W / 2 + 0.0012
    prof = [(0.0023, z0), (0.0085, z0), (0.0088, z0 + 0.0004), (0.0085, z0 + 0.0008), (GUIDE_R, z0 + 0.0009),
            (GUIDE_R, z1 - 0.0009), (0.0085, z1 - 0.0008), (0.0088, z1 - 0.0004), (0.0085, z1), (0.0023, z1)]
    add_obj(f"{name}_Sleeve", lathe_mesh(f"{name}_Sleeve", prof, seg=64, closed=True), C_TRANSPORT, M_STEEL,
            (c.x, c.y, 0), parent=rig)
    add_obj(f"{name}_Cap", lathe_mesh(f"{name}_Cap", [(0, 0), (0.0034, 0), (0.0034, 0.0008), (0.0024, 0.0016),
                                                         (0, 0.0018)], seg=32), C_TRANSPORT, M_CHROME,
            (c.x, c.y, z1 + 0.00005))
    drive(rig, "rotation_euler", 2, transport_expr(TAPE_SPEED / GUIDE_R))
    return rig


guide_roller("Guide_Roller_Supply", G1)
guide_roller("Guide_Roller_Takeup", G2)

# capstan with bearing housing and flywheel-driven shaft
add_obj("Capstan_Bearing", lathe_mesh("Capstan_Bearing", [(0, 0), (0.0065, 0), (0.0065, 0.0035), (0.0055, 0.0050),
                                                          (0.0040, 0.0052), (0, 0.0052)], seg=48), C_TRANSPORT,
        M_CHROME, (CAPSTAN.x, CAPSTAN.y, Z_DECK))
cap_rig = empty("RIG_Capstan", (CAPSTAN.x, CAPSTAN.y, Z_DECK), size=0.008)
add_obj("Capstan_Shaft", lathe_mesh("Capstan_Shaft", [(0, 0.0050), (CAPSTAN_R, 0.0050), (CAPSTAN_R, 0.0208),
                                                     (CAPSTAN_R * 0.7, 0.0214), (0, 0.0215)], seg=48),
        C_TRANSPORT, M_STEEL, (CAPSTAN.x, CAPSTAN.y, Z_DECK), parent=cap_rig)
drive(cap_rig, "rotation_euler", 2, transport_expr(TAPE_SPEED / CAPSTAN_R))

# pinch roller on a swinging arm
add_obj("PinchArm_PivotPost", lathe_mesh("PinchArm_PivotPost", [(0, 0), (0.0042, 0), (0.0042, 0.0010), (0.0030, 0.0012),
                                                               (0.0030, 0.0068), (0.0034, 0.0068), (0.0034, 0.0076),
                                                               (0, 0.0076)], seg=40), C_TRANSPORT, M_CHROME,
        (PINCH_PIVOT.x, PINCH_PIVOT.y, Z_DECK))
arm_rig = empty("RIG_PinchArm", (PINCH_PIVOT.x, PINCH_PIVOT.y, Z_DECK), size=0.01)
dvec = PINCH - PINCH_PIVOT
ang = atan2(dvec.y, dvec.x)
ln = dvec.length
arm_pts = []
for a in range(90, 271, 10):
    arm_pts.append((ln + 0.0055 * cos(radians(a - 180)), 0.0055 * sin(radians(a - 180))))
for a in range(-90, 91, 10):
    arm_pts.append((0.0050 * cos(radians(a + 180)), 0.0050 * sin(radians(a + 180))))
arm_pts = [(PINCH_PIVOT.x + x * cos(ang) - y * sin(ang), PINCH_PIVOT.y + x * sin(ang) + y * cos(ang))
           for x, y in arm_pts]
arm_hole = circle(PINCH_PIVOT.x, PINCH_PIVOT.y, 0.0031, 32)
arm = add_obj("PinchArm", profile_mesh("PinchArm", [arm_pts, arm_hole], Z_DECK + 0.0040, Z_DECK + 0.0062), C_TRANSPORT,
              M_BLACK_ANOD, parent=arm_rig)
bevel(arm, 0.0005, 2)
pr_z0 = Z_TAPE - 0.0049
pr_z1 = Z_TAPE + 0.0049
add_obj("PinchRoller_Axle", lathe_mesh("PinchRoller_Axle", [(0, Z_DECK + 0.0062), (0.0016, Z_DECK + 0.0062),
                                                             (0.0016, pr_z1 + 0.0016), (0, pr_z1 + 0.0016)], seg=24),
        C_TRANSPORT, M_CHROME, (PINCH.x, PINCH.y, 0), parent=arm_rig)
roll_rig = empty("RIG_PinchRoller", (PINCH.x, PINCH.y, 0), size=0.008, parent=arm_rig)
add_obj("PinchRoller_Rubber", lathe_mesh("PinchRoller_Rubber", [(0.0032, pr_z0), (PINCH_R - 0.0008, pr_z0),
                                                                 (PINCH_R, pr_z0 + 0.0008), (PINCH_R, pr_z1 - 0.0008),
                                                                 (PINCH_R - 0.0008, pr_z1), (0.0032, pr_z1)],
                                         seg=96, closed=True), C_TRANSPORT, M_RUBBER, (PINCH.x, PINCH.y, 0),
        parent=roll_rig)
add_obj("PinchRoller_Hub", lathe_mesh("PinchRoller_Hub", [(0.0016, pr_z0 - 0.0008), (0.0046, pr_z0 - 0.0008),
                                                           (0.0046, pr_z1 + 0.0004), (0.0040, pr_z1 + 0.0012),
                                                           (0.0016, pr_z1 + 0.0012)], seg=48, closed=True),
        C_TRANSPORT, M_CHROME, (PINCH.x, PINCH.y, 0), parent=roll_rig)
drive(roll_rig, "rotation_euler", 2, "-" + transport_expr(TAPE_SPEED / PINCH_R))
text("TXT_Deck_Speed", "9.5 / 19 cm/s", 0.0024, (0.097, -0.0470, Z_DECK + 0.00003), mat=M_INK_K)


# ---------------------------------------------------------------------------
# 8. REELS (separately modelled: two spoked flanges, hub, tape pack, spindle)
# ---------------------------------------------------------------------------
def flange_profile():
    outer = circle(0, 0, REEL_RADIUS, 160)
    holes = [circle(0, 0, 0.0036, 32)]
    w = 0.0052
    for k in range(3):
        s0 = radians(90 + 120 * k)
        s1 = s0 + radians(120)
        r_in, r_out = 0.0215, 0.0565
        pts = []
        a_start, a_end = s0 + asin(w / r_out), s1 - asin(w / r_out)
        for i in range(25):
            a = a_start + (a_end - a_start) * i / 24
            pts.append((r_out * cos(a), r_out * sin(a)))
        for i in range(1, 8):
            r = r_out + (r_in - r_out) * i / 8
            a = s1 - asin(w / r)
            pts.append((r * cos(a), r * sin(a)))
        a_start, a_end = s1 - asin(w / r_in), s0 + asin(w / r_in)
        for i in range(13):
            a = a_start + (a_end - a_start) * i / 12
            pts.append((r_in * cos(a), r_in * sin(a)))
        for i in range(1, 8):
            r = r_in + (r_out - r_in) * i / 8
            a = s0 + asin(w / r)
            pts.append((r * cos(a), r * sin(a)))
        holes.append(smooth_poly(pts, 2))
    return [outer] + holes


FL_LOOPS = flange_profile()
FL_T = 0.0012
Z_FL_IN_B = Z_TAPE - TAPE_W / 2 - 0.0005     # inner face of lower flange
Z_FL_IN_T = Z_TAPE + TAPE_W / 2 + 0.0005     # inner face of upper flange


def build_reel(tag, c, pack_r):
    rig = empty(f"RIG_Reel_{tag}", (c.x, c.y, Z_DECK), size=0.03, kind='CIRCLE')
    rig.rotation_euler = (0, 0, 0)
    add_obj(f"Spindle_{tag}_Collar", lathe_mesh(f"Spindle_{tag}_Collar", [(0.0125, 0), (0.0235, 0), (0.0235, 0.0007),
                                                                          (0.0225, 0.0010), (0.0125, 0.0010)],
                                                seg=96, closed=True), C_REELS, M_CHROME, (c.x, c.y, Z_DECK))
    tt = lathe_mesh(f"Reel_{tag}_Turntable", [(0, 0), (0.0120, 0), (0.0120, 0.0020), (0.0105, 0.0026),
                                              (0.0105, Z_FL_IN_B - FL_T - Z_DECK), (0, Z_FL_IN_B - FL_T - Z_DECK)],
                    seg=64)
    add_obj(f"Reel_{tag}_Turntable", tt, C_REELS, M_BLACK_ANOD, (c.x, c.y, Z_DECK), parent=rig)
    fb = add_obj(f"Reel_{tag}_Flange_Lower", profile_mesh(f"Reel_{tag}_Flange", FL_LOOPS, Z_FL_IN_B - FL_T, Z_FL_IN_B),
                 C_REELS, M_SPUN, (c.x, c.y, 0), parent=rig)
    ft = add_obj(f"Reel_{tag}_Flange_Upper", profile_mesh(f"Reel_{tag}_FlangeU", FL_LOOPS, Z_FL_IN_T, Z_FL_IN_T + FL_T),
                 C_REELS, M_SPUN, (c.x, c.y, 0), parent=rig)
    for f in (fb, ft):
        bevel(f, 0.0003, 2, angle=40)
    hub = lathe_mesh(f"Reel_{tag}_Hub", [(0.0036, Z_FL_IN_B + 0.00002), (HUB_R, Z_FL_IN_B + 0.00002),
                                         (HUB_R, Z_FL_IN_T - 0.00002), (0.0036, Z_FL_IN_T - 0.00002)],
                     seg=96, closed=True)
    add_obj(f"Reel_{tag}_Hub", hub, C_REELS, M_BAKELITE, (c.x, c.y, 0), parent=rig)
    # hub slot (tape anchoring) visible through the windows
    add_obj(f"Reel_{tag}_HubSlot", box_mesh(f"Reel_{tag}_HubSlot", 0.0010, 0.006, Z_FL_IN_T - Z_FL_IN_B - 0.0002),
            C_REELS, M_RECESS, (c.x + HUB_R - 0.0004, c.y, Z_TAPE), parent=rig)
    zt = Z_FL_IN_T + FL_T
    boss = lathe_mesh(f"Reel_{tag}_Boss", [(0.0036, zt), (0.0098, zt), (0.0098, zt + 0.0010), (0.0090, zt + 0.0016),
                                           (0.0036, zt + 0.0016)], seg=64, closed=True)
    add_obj(f"Reel_{tag}_Boss", boss, C_REELS, M_SPUN, (c.x, c.y, 0), parent=rig)
    pack = lathe_mesh(f"Reel_{tag}_TapePack", [(HUB_R, Z_TAPE - TAPE_W / 2), (pack_r, Z_TAPE - TAPE_W / 2),
                                               (pack_r, Z_TAPE + TAPE_W / 2), (HUB_R, Z_TAPE + TAPE_W / 2)],
                      seg=160, closed=True)
    add_obj(f"Reel_{tag}_TapePack", pack, C_REELS, M_TAPE, (c.x, c.y, 0), parent=rig)
    shaft = lathe_mesh(f"Spindle_{tag}_Shaft", [(0, Z_DECK + 0.0026), (0.0030, Z_DECK + 0.0026),
                                                (0.0030, zt + 0.0020), (0, zt + 0.0020)], seg=32)
    add_obj(f"Spindle_{tag}_Shaft", shaft, C_REELS, M_STEEL, (c.x, c.y, 0), parent=rig)
    for k in range(3):
        a = radians(30 + 120 * k)
        add_obj(f"Spindle_{tag}_Dog_{k}", box_mesh(f"Spindle_{tag}_Dog", 0.0032, 0.0012, 0.0014), C_REELS, M_STEEL,
                (c.x + 0.0047 * cos(a), c.y + 0.0047 * sin(a), zt + 0.0023), (0, 0, a), parent=rig)
    lock = lathe_mesh(f"Spindle_{tag}_LockCap", [(0, zt + 0.0018), (0.0064, zt + 0.0018), (0.0064, zt + 0.0050),
                                                 (0.0056, zt + 0.0058), (0.0030, zt + 0.0062), (0, zt + 0.0062)],
                      seg=120, knurl=(24, 0.0004, zt + 0.0019, zt + 0.0049))
    add_obj(f"Spindle_{tag}_LockCap", lock, C_REELS, M_CHROME, (c.x, c.y, 0), parent=rig)
    # angular speed = tape speed / pack radius (both reels turn counter-clockwise for this route)
    drive(rig, "rotation_euler", 2, transport_expr(TAPE_SPEED / pack_r))
    rig["tape_pack_radius_m"] = pack_r
    rig["angular_speed_rad_s"] = TAPE_SPEED / pack_r
    return rig


build_reel("Supply", REEL_L, PACK_SUPPLY)
build_reel("Takeup", REEL_R, PACK_TAKEUP)
text("TXT_Deck_Supply", "SUPPLY", 0.0030, (-0.088, -0.0150, Z_DECK + 0.00003), mat=M_INK_K, spacing=1.15)
text("TXT_Deck_Takeup", "TAKE-UP", 0.0030, (0.090, -0.0150, Z_DECK + 0.00003), mat=M_INK_K, spacing=1.15)


def rotation_arrow(name, c, r, a0, a1):
    band = arc_band(c.x, c.y, r - 0.0004, r + 0.0004, radians(a0), radians(a1), 30)
    tip_a = radians(a1)
    t = Vector((-sin(tip_a), cos(tip_a)))
    n = Vector((cos(tip_a), sin(tip_a)))
    tip = Vector((c.x, c.y)) + n * r
    head = [tuple(tip + n * 0.0016), tuple(tip + t * 0.0030), tuple(tip - n * 0.0016)]
    add_obj(name, flat_mesh(name, [band, head]), C_MARKINGS, M_INK_K, (0, 0, Z_DECK + 0.00001))


rotation_arrow("MRK_Arrow_Supply", REEL_L, 0.0685, 105, 150)
rotation_arrow("MRK_Arrow_Takeup", REEL_R, 0.0685, 30, 75)
text("TXT_Deck_ReelMax", "REEL  MAX  13 cm", 0.0024, (0.0, 0.122, Z_DECK + 0.00003), mat=M_INK_K, spacing=1.1)


# ---------------------------------------------------------------------------
# 9. CONTINUOUS TAPE ROUTE (computed belt tangents around every element)
# ---------------------------------------------------------------------------
def tangent_line(c1, r1, s1, c2, r2, s2):
    """Tangent from circle 1 to circle 2 travelling with sense s (+1 CCW, -1 CW)."""
    Dv = Vector((c2.x - c1.x, c2.y - c1.y))
    k = r2 * s2 - r1 * s1
    phi = atan2(Dv.y, Dv.x)
    th = phi + asin(-k / Dv.length)
    d = Vector((cos(th), sin(th)))
    Rn = Vector((d.y, -d.x))
    p1 = Vector((c1.x, c1.y)) + Rn * (r1 * s1)
    p2 = Vector((c2.x, c2.y)) + Rn * (r2 * s2)
    return p1, p2


def arc_pts(c, r, a_from, a_to, s, step=radians(3)):
    if s > 0:
        while a_to < a_from:
            a_to += 2 * pi
    else:
        while a_to > a_from:
            a_to -= 2 * pi
    n = max(2, int(abs(a_to - a_from) / step) + 1)
    return [Vector((c.x + r * cos(a_from + (a_to - a_from) * i / n), c.y + r * sin(a_from + (a_to - a_from) * i / n)))
            for i in range(n + 1)]


ROUTE = [("Reel_Supply_TapePack", REEL_L, PACK_SUPPLY + TOFF, 1),
         ("Guide_Roller_Supply", G1, GUIDE_R + TOFF, 1),
         ("Capstan_Shaft", CAPSTAN, CAPSTAN_R + TOFF, 1),
         ("Guide_Roller_Takeup", G2, GUIDE_R + TOFF, 1),
         ("Reel_Takeup_TapePack", REEL_R, PACK_TAKEUP + TOFF, 1)]
tangents = [tangent_line(a[1], a[2], a[3], b[1], b[2], b[3]) for a, b in zip(ROUTE, ROUTE[1:])]
path = []
# last wraps on the supply pack before the tape leaves it
p_out = tangents[0][0]
a_out = atan2(p_out.y - REEL_L.y, p_out.x - REEL_L.x)
path += arc_pts(REEL_L, ROUTE[0][2], a_out - radians(40), a_out, 1)
for i in range(1, len(ROUTE) - 1):
    nm, c, r, s = ROUTE[i]
    p_in = tangents[i - 1][1]
    p_out = tangents[i][0]
    a_in = atan2(p_in.y - c.y, p_in.x - c.x)
    a_o = atan2(p_out.y - c.y, p_out.x - c.x)
    seg_pts = arc_pts(c, r, a_in, a_o, s) if (p_in - p_out).length > 1e-6 else [p_in]
    path += seg_pts
p_in = tangents[-1][1]
a_in = atan2(p_in.y - REEL_R.y, p_in.x - REEL_R.x)
path += arc_pts(REEL_R, ROUTE[-1][2], a_in, a_in + radians(40), 1)
# densify long straight runs so the ribbon can be inspected/deformed
dense = [path[0]]
for p in path[1:]:
    q = dense[-1]
    L_ = (p - q).length
    if L_ < 1e-7:
        continue
    n = max(1, int(L_ / 0.004))
    for k in range(1, n + 1):
        dense.append(q.lerp(p, k / n))
tv, tf = [], []
for i, p in enumerate(dense):
    tv += [(p.x, p.y, Z_TAPE - TAPE_W / 2), (p.x, p.y, Z_TAPE + TAPE_W / 2)]
    if i:
        a = 2 * (i - 1)
        tf.append((a, a + 2, a + 3, a + 1))
tme = bpy.data.meshes.new("Tape_Route")
tme.from_pydata(tv, [], tf)
tme.shade_smooth()
tape = add_obj("Tape_Route_Ribbon", tme, C_TAPE, M_TAPE)
so = tape.modifiers.new("Solidify_TapeThickness", 'SOLIDIFY')
so.thickness = TAPE_T
so.offset = 0.0
tape["route"] = " > ".join(r[0] for r in ROUTE)
tape["route_length_m"] = sum((b - a).length for a, b in zip(dense, dense[1:]))

# ---------------------------------------------------------------------------
# 10. LID (hinged tray, felt lining, threading diagram plate, keeper)
# ---------------------------------------------------------------------------
lid_rig = empty("RIG_Lid_Hinge", HINGE, size=0.04, kind='ARROWS')
lid = add_obj("Lid_Shell", profile_mesh("Lid_Shell", [OUTLINE], Z_BODY_TOP, Z_BODY_TOP + LID_H, bottom=False),
              C_LID, M_CASE, parent=lid_rig)
sd = lid.modifiers.new("Solidify_Wall", 'SOLIDIFY')
sd.thickness = 0.003
sd.offset = -1.0
sd.use_even_offset = True
bevel(lid, 0.0022, 3)
z_in = Z_BODY_TOP + LID_H - 0.003
add_obj("Lid_Felt_Lining", profile_mesh("Lid_Felt_Lining", [rrect(0, 0, W - 0.0075, D - 0.0075, R_CORNER - 0.0035, 8)],
                                        z_in - 0.0025, z_in - 0.00002), C_LID, M_FELT, parent=lid_rig)
PL_C = Vector((0.0, -0.050))
z_pl = z_in - 0.0025
plate = add_obj("Lid_Threading_Plate", profile_mesh("Lid_Threading_Plate",
                [rrect(PL_C.x, PL_C.y, 0.230, 0.100, 0.004, 5)], z_pl - 0.0008, z_pl), C_LID, M_ALU, parent=lid_rig)
bevel(plate, 0.0003, 2)
for sx in (-0.110, 0.110):
    for sy in (-0.044, 0.044):
        screw((PL_C.x + sx, PL_C.y + sy, z_pl - 0.0008), (0, 0, -1), 0.0013, parent=lid_rig)
# threading diagram drawn from the real tape route (scaled), printed on the plate
SC = 0.40
DGO = Vector((-0.050, 0.0))     # diagram origin in plate (u, v) space


def to_uv(p):
    return Vector(((p.x * SC) + DGO.x, (p.y - 0.030) * SC + DGO.y))


diag = []
for a, b in zip(dense[::3], dense[3::3] + [dense[-1]]):
    ua, ub = to_uv(a), to_uv(b)
    t = (ub - ua)
    if t.length < 1e-7:
        continue
    nrm = Vector((-t.y, t.x)).normalized() * 0.00035
    diag.append([tuple(ua - nrm), tuple(ub - nrm), tuple(ub + nrm), tuple(ua + nrm)])
for c, rr in ((REEL_L, REEL_RADIUS), (REEL_R, REEL_RADIUS), (REEL_L, HUB_R), (REEL_R, HUB_R)):
    cc = to_uv(c)
    diag.append(arc_band(cc.x, cc.y, rr * SC - 0.0003, rr * SC + 0.0003, 0, 2 * pi - 0.001, 64))
for c, rr in ((G1, GUIDE_R), (G2, GUIDE_R), (CAPSTAN, 0.0035), (PINCH, PINCH_R)):
    cc = to_uv(c)
    diag.append(circle(cc.x, cc.y, max(rr * SC, 0.0012), 24))
for nm, hx in HEADS:
    cc = to_uv(Vector((hx, -0.024)))
    diag.append(rrect(cc.x, cc.y, 0.0040, 0.0026, 0.0003, 1))
diag_me = flat_mesh("MRK_Threading_Diagram", diag, 0.00004)
add_obj("MRK_Threading_Diagram", diag_me, C_LID, M_INK_K, (PL_C.x, PL_C.y, z_pl - 0.0008), ROT_DOWN, parent=lid_rig)
lines = ["STRATON  FR-74  REPORTER", "TAPE THREADING", "", "TAPE  6.3 mm   REEL  13 cm MAX",
         "SPEED  9.5 / 19 cm/s   +/- 0.2 %", "POWER  6 x 1.5 V  R20  /  EXT 9 V",
         "BIAS  80 kHz      EQ  CCIR", "No. 74-03118"]
for i, ln_ in enumerate(lines):
    if not ln_:
        continue
    text(f"TXT_LidPlate_{i}", ln_, 0.0050 if i == 0 else 0.0032,
         (PL_C.x + 0.020, PL_C.y - 0.036 + i * 0.0095, z_pl - 0.00083), ROT_DOWN,
         M_INK_R if i == 0 else M_INK_K, C_LID, align='LEFT', parent=lid_rig, spacing=1.08)
# lid keeper for the latch + lid hinge leaf
kp = add_obj("Lid_Latch_Keeper", box_mesh("Lid_Latch_Keeper", 0.016, 0.0034, 0.0040), C_LID, M_CHROME,
             (0, -D / 2 - 0.0017, Z_BODY_TOP + 0.0070), parent=lid_rig)
bevel(kp, 0.0006, 2)
leaf_l = add_obj("Hinge_Leaf_Lid", box_mesh("Hinge_Leaf_Lid", 0.30, 0.0012, 0.010), C_LID, M_CHROME,
                 (0, D / 2 + 0.0006, Z_BODY_TOP + 0.0085), parent=lid_rig)
bevel(leaf_l, 0.0003, 2)
for hx in (-0.12, -0.04, 0.04, 0.12):
    screw((hx, D / 2 + 0.0013, Z_BODY_TOP + 0.0085), (0, 1, 0), 0.0011, parent=lid_rig)
text("TXT_Lid_Brand", "STRATON", 0.016, (0, -0.02, Z_BODY_TOP + LID_H + 0.00004), mat=M_INK_W, coll=C_LID,
     parent=lid_rig, spacing=1.3)

# ---------------------------------------------------------------------------
# 11. ANIMATION 1-120: latch releases, lid opens, PLAY engages, transport runs
# ---------------------------------------------------------------------------
SCENE.render.fps = FPS
SCENE.frame_start, SCENE.frame_end = FRAME_START, FRAME_END


def key(ob, path, idx, frame, value):
    getattr(ob, path)[idx] = value
    ob.keyframe_insert(data_path=path, index=idx, frame=frame)


key(latch_rig, "rotation_euler", 0, 1, 0.0)
key(latch_rig, "rotation_euler", 0, 4, 0.0)
key(latch_rig, "rotation_euler", 0, 14, radians(175))
key(lid_rig, "rotation_euler", 0, 1, 0.0)
key(lid_rig, "rotation_euler", 0, 12, 0.0)
key(lid_rig, "rotation_euler", 0, 60, -radians(LID_OPEN_DEG))
key(KEY_RIGS["PLAY"], "location", 1, 30, KEY_RIGS["PLAY"].location.y)
key(KEY_RIGS["PLAY"], "location", 1, 36, KEY_RIGS["PLAY"].location.y + 0.0045)
key(arm_rig, "rotation_euler", 2, 1, radians(12))
key(arm_rig, "rotation_euler", 2, 34, radians(12))
key(arm_rig, "rotation_euler", 2, 40, 0.0)

# ---------------------------------------------------------------------------
# 12. STUDIO: seamless sweep backdrop, lights, world
# ---------------------------------------------------------------------------
prof = [(-2.0, 0.0)]
for i in range(0, 25):
    a = radians(-90 + 90 * i / 24)
    prof.append((0.55 + 0.6 * cos(a), 0.6 + 0.6 * sin(a)))
prof.append((1.15, 2.2))
bv, bf = [], []
for x in (-3.0, 3.0):
    for (y, z) in prof:
        bv.append((x, y, z))
n = len(prof)
for i in range(n - 1):
    bf.append((i, i + 1, n + i + 1, n + i))
bme = bpy.data.meshes.new("Studio_Sweep")
bme.from_pydata(bv, [], bf)
bme.shade_smooth()
sweep = add_obj("Studio_Sweep", bme, C_STUDIO, M_BACKDROP)
for f in sweep.data.polygons:
    pass
sweep.rotation_euler = (0, 0, radians(38))

world = bpy.data.worlds.new("World_Studio")
SCENE.world = world
world.use_nodes = True
bg = world.node_tree.nodes.get("Background")
bg.inputs["Color"].default_value = (0.012, 0.012, 0.014, 1)
bg.inputs["Strength"].default_value = 1.0


def area_light(name, loc, target, energy, size, size_y=None, color=(1, 1, 1)):
    ld = bpy.data.lights.new(name, 'AREA')
    ld.energy = energy
    ld.color = color
    ld.shape = 'RECTANGLE' if size_y else 'SQUARE'
    ld.size = size
    if size_y:
        ld.size_y = size_y
    ob = add_obj(name, ld, C_LIGHTS, None, loc)
    d = Vector(target) - Vector(loc)
    ob.rotation_euler = d.to_track_quat('-Z', 'Y').to_euler()
    return ob


TARGET = (0.0, 0.0, 0.10)
area_light("Light_Key_Softbox", (-0.85, -0.75, 1.05), TARGET, 120, 1.1, 0.8, (1.0, 0.97, 0.93))
area_light("Light_Fill", (1.25, -0.55, 0.35), TARGET, 22, 1.4, 1.0, (0.92, 0.96, 1.0))
area_light("Light_Rim_Strip", (0.55, 0.95, 0.75), TARGET, 110, 0.25, 1.6, (1.0, 1.0, 1.0))
area_light("Light_Top", (0.0, -0.05, 1.35), TARGET, 18, 1.2, 1.2)
area_light("Light_Kicker_Left", (-1.0, 0.6, 0.45), TARGET, 30, 0.3, 1.0, (0.95, 0.97, 1.0))


# ---------------------------------------------------------------------------
# 13. CAMERAS
# ---------------------------------------------------------------------------
def camera(name, loc, target, lens, fstop=None, focus=None, sensor=36.0):
    cd = bpy.data.cameras.new(name)
    cd.lens = lens
    cd.sensor_width = sensor
    cd.clip_start = 0.01
    ob = add_obj(name, cd, C_CAMS, None, loc)
    d = Vector(target) - Vector(loc)
    ob.rotation_euler = d.to_track_quat('-Z', 'Y').to_euler()
    if fstop:
        cd.dof.use_dof = True
        cd.dof.aperture_fstop = fstop
        fe = empty(f"{name}_Focus", focus or target, C_CAMS, 0.01)
        cd.dof.focus_object = fe
    return ob


CAM_HERO = camera("CAM_Hero", (0.80, -1.02, 0.70), (-0.005, 0.030, 0.170), 55, 11, (0.02, -0.03, 0.12))
CAM_DETAIL = camera("CAM_Detail", (0.20, -0.22, 0.21), (0.0, -0.045, 0.112), 60, 8.0, (0.035, -0.045, 0.116))
SCENE.camera = CAM_HERO

# ---------------------------------------------------------------------------
# 14. RENDER SETTINGS (Cycles GPU -> CPU fallback, Eevee fallback)
# ---------------------------------------------------------------------------
RENDER_INFO = {}


def setup_render(scene, samples):
    try:
        scene.render.engine = 'CYCLES'
    except Exception:
        for eng in ('BLENDER_EEVEE', 'BLENDER_EEVEE_NEXT'):
            try:
                scene.render.engine = eng
                RENDER_INFO["engine"] = eng + " (fallback, Cycles unavailable)"
                return
            except Exception:
                pass
    RENDER_INFO["engine"] = "CYCLES"
    device = "CPU"
    if not FORCE_CPU:
        try:
            prefs = bpy.context.preferences.addons["cycles"].preferences
            for backend in ("OPTIX", "CUDA", "HIP", "ONEAPI", "METAL"):
                try:
                    prefs.compute_device_type = backend
                    prefs.get_devices()
                except Exception:
                    continue
                gpus = [d for d in prefs.devices if d.type == backend]
                if gpus:
                    for d in prefs.devices:
                        d.use = d.type == backend
                    device = backend
                    break
        except Exception as e:
            print("GPU detection failed:", e)
    scene.cycles.device = 'GPU' if device != "CPU" else 'CPU'
    RENDER_INFO["device"] = device
    scene.cycles.samples = samples
    scene.cycles.use_adaptive_sampling = True
    scene.cycles.adaptive_threshold = 0.012
    scene.cycles.use_denoising = True
    try:
        scene.cycles.denoiser = 'OPENIMAGEDENOISE'
        scene.cycles.denoising_use_gpu = device != "CPU"
    except Exception:
        pass
    scene.cycles.max_bounces = 12
    scene.cycles.glossy_bounces = 6
    scene.cycles.transmission_bounces = 12
    scene.cycles.caustics_reflective = False
    scene.cycles.caustics_refractive = False
    scene.cycles.blur_glossy = 0.5
    scene.cycles.sample_clamp_indirect = 8.0
    scene.render.resolution_x = 1920
    scene.render.resolution_y = 1080
    scene.render.resolution_percentage = 100
    scene.render.image_settings.file_format = 'PNG'
    scene.render.image_settings.color_mode = 'RGB'
    scene.render.image_settings.color_depth = '8'
    scene.view_settings.view_transform = 'AgX'
    for look in ("AgX - Medium High Contrast", "Medium High Contrast"):
        try:
            scene.view_settings.look = look
            break
        except Exception:
            pass
    scene.view_settings.exposure = -0.6
    scene.render.use_motion_blur = False


setup_render(SCENE, SAMPLES)

# ---------------------------------------------------------------------------
# 15. EXPLODED TECHNICAL VIEW (secondary scene, frozen geometry copies)
# ---------------------------------------------------------------------------
SCENE.frame_set(1)
bpy.context.view_layer.update()
dg = bpy.context.evaluated_depsgraph_get()
EXP = bpy.data.scenes.new("Exploded_View")
EXP.render.fps = FPS
EXP.frame_start, EXP.frame_end = 1, 1
exp_coll = bpy.data.collections.new("EXPLODED_Parts")
EXP.collection.children.link(exp_coll)
n_copied = 0
for coll in C_REC.children:
    if coll.name not in EXPLODE:
        continue
    off = Vector(EXPLODE[coll.name])
    for ob in coll.objects:
        if ob.type not in {'MESH', 'CURVE', 'FONT'} or ob.hide_render:
            continue
        ev = ob.evaluated_get(dg)
        try:
            me = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=False, depsgraph=dg)
        except Exception:
            continue
        if me is None or len(me.vertices) == 0:
            continue
        me.name = "EXP_" + ob.name
        cp = bpy.data.objects.new("EXP_" + ob.name, me)
        exp_coll.objects.link(cp)
        mw = ev.matrix_world.copy()
        # markings follow the surface they are printed on
        o2 = off
        if coll.name == "REC_Markings":
            if mw.translation.z > Z_DECK - 0.001 and mw.translation.y < -0.055 and abs(mw.translation.y) < D / 2 - 0.001:
                o2 = Vector(EXPLODE["REC_Controls"])
            elif mw.translation.z > Z_DECK - 0.001 and abs(mw.translation.y) < D / 2 - 0.001:
                o2 = Vector(EXPLODE["REC_Deck"])
        if ob.name.startswith("Key_"):
            o2 = Vector((0, -0.07, 0))
        cp.matrix_world = Matrix.Translation(o2) @ mw
        n_copied += 1
# hardware screws on deck/control plate follow their plates
for cp in exp_coll.objects:
    if cp.name.startswith("EXP_HW_Screw"):
        z = cp.matrix_world.translation.z
        y = cp.matrix_world.translation.y
        if abs(z - Z_CTRL) < 0.0005:
            cp.matrix_world.translation.z += EXPLODE["REC_Controls"][2]
        elif abs(z - Z_DECK) < 0.0005 and abs(y) < D / 2 - 0.002:
            cp.matrix_world.translation.z += EXPLODE["REC_Deck"][2]
        elif Z_DECK + 0.001 < z < Z_DECK + 0.03 and abs(y) < D / 2 - 0.002:
            cp.matrix_world.translation.z += EXPLODE["REC_Transport"][2]
# leader / axis lines + callouts
lead_mat = mat_plastic("M_Exploded_Leader", (0.15, 0.25, 0.55), 0.5, micro=0.0)
for nm, c, z0, z1 in (("Reel_Supply", REEL_L, Z_DECK, Z_DECK + 0.29), ("Reel_Takeup", REEL_R, Z_DECK, Z_DECK + 0.29),
                      ("Capstan", CAPSTAN, Z_DECK, Z_DECK + 0.23)):
    for k in range(int((z1 - z0) / 0.008)):
        za = z0 + k * 0.008
        me = lathe_mesh("EXP_Lead", [(0, 0), (0.0006, 0), (0.0006, 0.005), (0, 0.005)], seg=8, smooth=False)
        me.materials.append(lead_mat)
        o = bpy.data.objects.new(f"EXP_Lead_{nm}_{k}", me)
        exp_coll.objects.link(o)
        o.location = (c.x, c.y, za)
callouts = [("1  HOUSING / CASE", 0.06), ("2  DECK PLATE + VU METERS", Z_DECK + 0.12),
            ("3  CONTROL PANEL", Z_CTRL + 0.20), ("4  TAPE TRANSPORT", Z_TAPE + 0.27),
            ("5  REELS  13 cm", Z_TAPE + 0.34), ("6  HINGED LID", Z_BODY_TOP + 0.02 + 0.47)]
for i, (t, p) in enumerate(callouts):
    cu = bpy.data.curves.new(f"EXP_Callout_{i}", 'FONT')
    cu.body = t
    cu.size = 0.016
    cu.extrude = 0.0004
    cu.materials.append(lead_mat)
    o = bpy.data.objects.new(f"EXP_Callout_{i}", cu)
    exp_coll.objects.link(o)
    o.location = (0.215, 0.0, p - 0.006)
    o.rotation_euler = (radians(90), 0, radians(40))
    cu.align_x = 'LEFT'
    # short leader tick from the part edge to the label
    lme = box_mesh(f"EXP_CalloutLeader_{i}", 0.030, 0.0012, 0.0012)
    lme.materials.append(lead_mat)
    lo = bpy.data.objects.new(f"EXP_CalloutLeader_{i}", lme)
    exp_coll.objects.link(lo)
    lo.location = (0.195, 0.0, p)
ttl = bpy.data.curves.new("EXP_Title", 'FONT')
ttl.body = "FR-74  EXPLODED ASSEMBLY VIEW"
ttl.size = 0.022
ttl.materials.append(lead_mat)
o = bpy.data.objects.new("EXP_Title", ttl)
exp_coll.objects.link(o)
o.location = (-0.36, 0.05, 0.70)
o.rotation_euler = (radians(90), 0, radians(40))
ew = bpy.data.worlds.new("World_Exploded")
ew.color = (0.92, 0.92, 0.90)
EXP.world = ew
ecd = bpy.data.cameras.new("CAM_Exploded")
ecd.lens = 50
ecd.clip_start = 0.01
ecam = bpy.data.objects.new("CAM_Exploded", ecd)
exp_coll.objects.link(ecam)
ecam.location = (1.15, -1.30, 0.80)
ecam.rotation_euler = (Vector((0.03, 0.0, 0.32)) - ecam.location).to_track_quat('-Z', 'Y').to_euler()
EXP.camera = ecam
EXP.render.engine = 'BLENDER_WORKBENCH'
sh = EXP.display.shading
sh.light = 'STUDIO'
sh.color_type = 'SINGLE'
sh.single_color = (0.80, 0.80, 0.78)
sh.show_cavity = True
sh.cavity_type = 'BOTH'
sh.show_object_outline = True
sh.object_outline_color = (0.05, 0.05, 0.06)
sh.show_shadows = True
try:
    EXP.display.render_aa = '16'
except Exception:
    pass
EXP.view_settings.view_transform = 'Standard'
EXP.render.resolution_x = 1280
EXP.render.resolution_y = 960
EXP.render.image_settings.file_format = 'PNG'
print(f"Exploded view: {n_copied} frozen part copies")

# back to the presentation frame (lid open, transport running)
SCENE.frame_set(FRAME_END)

# ---------------------------------------------------------------------------
# 16. SAVE + RENDER
# ---------------------------------------------------------------------------
SCENE["render_engine_report"] = str(RENDER_INFO)
BLEND = os.path.join(OUT_DIR, "field_recorder.blend")
try:
    bpy.context.window_manager.windows[0].scene = SCENE
except Exception:
    pass
bpy.ops.wm.save_as_mainfile(filepath=BLEND, compress=True)
print("Saved", BLEND, RENDER_INFO)


def render_still(scene, cam, path, res=None, samples=None):
    scene.camera = cam
    if res:
        scene.render.resolution_x, scene.render.resolution_y = res
    if samples and scene.render.engine == 'CYCLES':
        scene.cycles.samples = samples
    scene.render.filepath = path
    bpy.ops.render.render(write_still=True, scene=scene.name)
    print("Rendered", path)


if DO_RENDER:
    pre = "preview_" if PREVIEW else ""
    res = (960, 540) if PREVIEW else (1920, 1080)
    spp = 64 if PREVIEW else SAMPLES
    SCENE.frame_set(FRAME_END)
    render_still(SCENE, CAM_HERO, os.path.join(OUT_DIR, pre + "hero.png"), res, spp)
    render_still(SCENE, CAM_DETAIL, os.path.join(OUT_DIR, pre + "detail.png"), res, spp)
    if PREVIEW:
        EXP.render.resolution_percentage = 50
    render_still(EXP, ecam, os.path.join(OUT_DIR, pre + "exploded.png"))
    EXP.render.resolution_percentage = 100
    SCENE.render.resolution_x, SCENE.render.resolution_y = 1920, 1080
    SCENE.cycles.samples = SAMPLES
    SCENE.camera = CAM_HERO

if DO_ANIM:
    SCENE.render.resolution_x, SCENE.render.resolution_y = 640, 360
    SCENE.cycles.samples = 24
    SCENE.camera = CAM_HERO
    ok = False
    try:
        try:
            SCENE.render.image_settings.media_type = 'VIDEO'
        except Exception:
            pass
        SCENE.render.image_settings.file_format = 'FFMPEG'
        SCENE.render.ffmpeg.format = 'MPEG4'
        SCENE.render.ffmpeg.codec = 'H264'
        SCENE.render.filepath = os.path.join(OUT_DIR, "anim_preview.mp4")
        ok = True
    except Exception as e:
        print("FFMPEG unavailable, writing PNG frames:", e)
        SCENE.render.image_settings.file_format = 'PNG'
        SCENE.render.filepath = os.path.join(OUT_DIR, "anim_frames", "frame_")
    bpy.ops.render.render(animation=True, scene=SCENE.name)
    try:
        SCENE.render.image_settings.media_type = 'IMAGE'
    except Exception:
        pass
    SCENE.render.image_settings.file_format = 'PNG'
    SCENE.render.resolution_x, SCENE.render.resolution_y = 1920, 1080
    SCENE.cycles.samples = SAMPLES
    SCENE.frame_set(FRAME_END)

if DO_RENDER or DO_ANIM:
    bpy.ops.wm.save_as_mainfile(filepath=BLEND, compress=True)
    print("Re-saved after rendering", BLEND)
print("BUILD_OK")
