"""Detailed four-seat playground roundabout. Run with Blender's background Python."""
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import bmesh
import v4lib as v4

v4.reset()

# Coated, zinc plated and molded playground finishes.
blue = v4.painted("deep_blue_powdercoat", (0.055, 0.19, 0.34), roughness=0.32)
red = v4.plastic("safety_red_moulded_HDPE", (0.78, 0.075, 0.045), roughness=0.38, texture=0.12)
navy = v4.painted("dark_blue_frame", (0.025, 0.065, 0.105), roughness=0.34)
steel = v4.metal("zinc_plated_steel", (0.72, 0.75, 0.76), roughness=0.32, brushed=False)
stainless = v4.metal("stainless_bearing", (0.57, 0.61, 0.64), roughness=0.24, brushed=True)
rubber = v4.rubber("black_grip", (0.045, 0.052, 0.058), roughness=0.78)
yellow = v4.plastic("yellow_bearing_cap", (0.95, 0.58, 0.035), roughness=0.35, texture=0.1)
concrete = v4.mat("cast_concrete", (0.34, 0.36, 0.37), roughness=0.92)
teal = v4.plastic("teal_HDPE_feature_seat", (0.02, 0.56, 0.64), roughness=0.38, texture=0.12)

base = v4.body("ground_base")
platform = v4.body("rotating_platform")

def ring_mesh(name, r_outer, r_inner, z_bottom, z_top, material, body, n=96):
    """Closed annular plate with clean inner and outer walls."""
    verts, faces = [], []
    for z in (z_bottom, z_top):
        for r in (r_inner, r_outer):
            for i in range(n):
                a = 2 * math.pi * i / n
                verts.append((r * math.cos(a), r * math.sin(a), z))
    # indices: bottom inner, bottom outer, top inner, top outer
    def idx(layer, rad, i): return layer * 2 * n + rad * n + (i % n)
    for i in range(n):
        j = i + 1
        faces += [
            (idx(1, 0, i), idx(1, 0, j), idx(1, 1, j), idx(1, 1, i)),
            (idx(0, 1, i), idx(0, 1, j), idx(0, 0, j), idx(0, 0, i)),
            (idx(0, 1, i), idx(1, 1, i), idx(1, 1, j), idx(0, 1, j)),
            (idx(0, 0, j), idx(1, 0, j), idx(1, 0, i), idx(0, 0, i)),
        ]
    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.children.get("Asset").objects.link(obj)
    obj.data.materials.append(material)
    bevel = obj.modifiers.new("soft_safety_edges", "BEVEL")
    bevel.width = 0.002
    bevel.segments = 3
    bevel.limit_method = "ANGLE"
    obj.modifiers.new("weighted_normals", "WEIGHTED_NORMAL")
    v4.part(obj, body)
    return obj

def radial(r, a, z):
    return (r * math.cos(a), r * math.sin(a), z)

def fastener(name, pos, axis, radius=0.008, height=0.004, material=steel, body=base):
    # Cylinder's local Z is steered onto the exposed mounting face normal.
    obj = v4.cylinder(name, radius, height, pos, segments=24, bevel=0.0007, material=material, body=body)
    obj.rotation_mode = 'QUATERNION'
    from mathutils import Vector
    obj.rotation_quaternion = Vector((0, 0, 1)).rotation_difference(Vector(axis).normalized())
    return obj

# Fixed foundation: broad radial feet, anchor pads and a substantial central post.
v4.cylinder("column_foot_flange", 0.115, 0.045, (0, 0, 0.045), bevel=0.004, material=navy, body=base)
# Raised concrete collar around the mast base makes the post visibly enter a footing.
v4.cylinder("central_concrete_footing", 0.23, 0.09, (0, 0, 0.045), bevel=0.015, material=concrete, body=base)
for k in range(4):
    a = math.pi / 4 + k * math.pi / 2
    p0, p1 = radial(0.055, a, 0.045), radial(0.43, a, 0.035)
    v4.rod(f"foundation_outtrigger_{k+1}", p0, p1, 0.035, square=True, bevel=0.005, material=navy, body=base)
    x, y, _ = p1
    # Small cast-concrete pads carry the plates and keep the anchors grounded.
    v4.box(f"concrete_footing_{k+1}", (0.22, 0.18, 0.03), (x, y, 0.015), rot=(0, 0, a),
           bevel=0.008, material=concrete, body=base)
    # Foot plate bears on the footing and carries two visible anchor heads.
    v4.box(f"anchor_foot_plate_{k+1}", (0.15, 0.105, 0.018), (x, y, 0.04), rot=(0, 0, a),
           bevel=0.005, material=blue, body=base)
    for side in (-1, 1):
        q = radial(0.43, a + side * 0.11, 0.052)
        fastener(f"anchor_bolt_{k+1}_{side}", q, (0, 0, 1), 0.009, 0.006, steel, base)

# Fixed centre column and bearing pedestal. The spindle finishes below the rotating sleeve.
v4.lathe("fixed_center_column", [(0, 0.07), (0.078, 0.07), (0.078, 0.31), (0.066, 0.39),
                                 (0.055, 0.425), (0.055, 0.447), (0, 0.447)],
         material=blue, body=base)
v4.cylinder("bearing_pedestal", 0.075, 0.045, (0, 0, 0.425), bevel=0.003, material=navy, body=base)
ring_mesh("lower_bearing_race", 0.042, 0.038, 0.447, 0.465, stainless, base, n=64)
v4.cylinder("fixed_spindle", 0.038, 0.095, (0, 0, 0.5025), bevel=0.001, material=stainless, body=base)
ring_mesh("fixed_bearing_collar", 0.093, 0.042, 0.447, 0.463, stainless, base, n=64)

# Rotating frame and annular anti-slip deck. All geometry below belongs to one rigid body.
ring_mesh("welded_outer_deck_frame", 0.755, 0.10, 0.255, 0.297, navy, platform)
ring_mesh("red_non_slip_deck_surface", 0.744, 0.10, 0.297, 0.306, red, platform)
ring_mesh("raised_kick_rim", 0.755, 0.735, 0.306, 0.316, blue, platform)

# Four radial underside braces distribute load from the deck to the rotating bearing sleeve.
for k in range(8):
    a = k * math.pi / 4
    v4.rod(f"underdeck_spoke_{k+1}", radial(0.15, a, 0.264), radial(0.71, a, 0.264), 0.018,
           square=True, bevel=0.002, material=blue, body=platform)

# Deep rotating shroud reaches from the low deck up to the bearing without
# touching the wider fixed bearing pedestal (3 mm radial clearance).
ring_mesh("rotating_center_shroud", 0.10, 0.078, 0.297, 0.447, blue, platform, n=64)
# The outer bridge clears the fixed collar, then meets the moving upper flange.
ring_mesh("rotating_flange_bridge", 0.12, 0.095, 0.447, 0.469, blue, platform, n=64)
ring_mesh("rotating_bearing_flange", 0.12, 0.078, 0.469, 0.489, stainless, platform, n=64)
# Rotating bearing sleeve surrounds the fixed spindle with 4 mm radial clearance.
ring_mesh("rotating_hub_sleeve", 0.08, 0.042, 0.469, 0.55, stainless, platform, n=64)
ring_mesh("upper_bearing_race", 0.041, 0.039, 0.471, 0.485, steel, platform, n=64)
v4.cylinder("hub_dust_cap", 0.055, 0.018, (0, 0, 0.559), bevel=0.005, material=yellow, body=platform)
v4.cylinder("hub_cap_button", 0.018, 0.004, (0, 0, 0.569), bevel=0.0015, material=steel, body=platform)
for k in range(8):
    a = 2 * math.pi * k / 8
    fastener(f"bearing_flange_bolt_{k+1}", radial(0.104, a, 0.492), (0, 0, 1),
             0.006, 0.006, steel, platform)

# A raised central grab ring surrounds the bearing cap and is braced to the shroud.
v4.torus("central_grab_ring", 0.145, 0.012, (0, 0, 0.55), material=blue, body=platform)
for k in range(4):
    a = k * math.pi / 2 + math.pi / 4
    v4.rod(f"central_grab_ring_brace_{k+1}", radial(0.115, a, 0.489), radial(0.145, a, 0.55),
           0.012, material=blue, body=platform)

# Molded grip ribs across the deck, aligned radially and kept below the raised rim.
for k in range(32):
    a = 2 * math.pi * k / 32
    # Four short ribs per radius make a convincing molded non-slip surface.
    for j, r in enumerate((0.20, 0.29, 0.38, 0.69)):
        tang = (-math.sin(a), math.cos(a), 0)
        center = radial(r, a, 0.309)
        p0 = (center[0] - tang[0] * 0.026, center[1] - tang[1] * 0.026, center[2])
        p1 = (center[0] + tang[0] * 0.026, center[1] + tang[1] * 0.026, center[2])
        v4.rod(f"deck_grip_{k+1}_{j+1}", p0, p1, 0.0025, material=yellow if j == 1 else navy, body=platform)

# Three concentric rows of moulded anti-slip dimples between the radial tread bars.
for row, radius in enumerate((0.215, 0.315, 0.70)):
    for k in range(48):
        a = 2 * math.pi * (k + (row % 2) * 0.5) / 48
        v4.sphere(f"tread_dimple_{row+1}_{k+1}", 0.0035, radial(radius, a, 0.3095),
                  segments=16, material=navy, body=platform)

# Radial segment seams in the moulded tread, kept between the four seat stations.
for k in range(8):
    a = math.pi / 8 + k * math.pi / 4
    for j, (r0, r1) in enumerate(((0.13, 0.32), (0.36, 0.73))):
        v4.rod(f"deck_segment_seam_{k+1}_{j+1}", radial(r0, a, 0.307), radial(r1, a, 0.307),
               0.001, material=navy, body=platform)

# Four inward-facing molded seats, with solid pedestals, softly radiused shells and back lips.
for k in range(4):
    a = k * math.pi / 2
    rot = (0, 0, a - math.pi / 2)  # local +Y points radially outward
    x, y, _ = radial(0.55, a, 0)
    v4.box(f"seat_pedestal_{k+1}", (0.22, 0.20, 0.075), (x, y, 0.3435), rot=rot,
           bevel=0.015, material=blue, body=platform)
    seat_material = teal if k == 0 else red
    seat = v4.box(f"moulded_seat_{k+1}", (0.33, 0.25, 0.055), (x, y, 0.408), rot=rot,
                  bevel=0.022, material=seat_material, body=platform)
    # Shallow spherical boolean makes a true dish in the moulded shell.
    seat_top = 0.408 + 0.055 / 2
    cutter = v4.sphere(f"seat_dish_cutter_{k+1}", 0.8, (x, y, seat_top + 0.8 - 0.012), segments=32)
    cutter.scale = (1.10, 0.88, 1.0)
    cutter.rotation_euler = rot
    v4.boolean(seat, cutter)
    # Recessed shell fixings sit near the rear shoulders, outside the dish.
    c, s = math.cos(rot[2]), math.sin(rot[2])
    for side in (-1, 1):
        lx, ly = side * 0.12, 0.075
        fix = (x + lx * c - ly * s, y + lx * s + ly * c, 0.437)
        fastener(f"seat_shell_fixing_{k+1}_{side}", fix, (0, 0, 1), 0.0045, 0.003, steel, platform)
    # Raised outer edge keeps the seat recognisable as an inward-facing bucket saddle.
    v4.box(f"seat_back_lip_{k+1}", (0.30, 0.052, 0.105), radial(0.665, a, 0.467), rot=rot,
           bevel=0.018, material=seat_material, body=platform)
    # A narrow molded front edge band is a visual seat-shell detail.
    v4.box(f"seat_front_edge_{k+1}", (0.27, 0.014, 0.012), radial(0.425, a, 0.429), rot=rot,
           bevel=0.004, material=yellow, body=platform)

    # Sloping welded brackets support the plinth on the deck at both sides.
    for side in (-1, 1):
        theta = a + side * 0.11 / 0.55
        v4.rod(f"seat_mount_bracket_{k+1}_{side}", radial(0.45, theta, 0.307), radial(0.49, theta, 0.378),
               0.009, material=steel, body=platform)

    # Pair of high tubular hand grips in front of the seat. Separate straight
    # welded members meet at the bends and at the deck mounting feet.
    for side in (-1, 1):
        theta = a + side * 0.12 / 0.30
        foot = radial(0.30, theta, 0.305)
        shoulder = radial(0.30, theta, 0.60)
        grip_end = radial(0.34, theta, 0.65)
        v4.rod(f"seat_grip_upright_{k+1}_{side}", foot, shoulder, 0.014, material=blue, body=platform)
        v4.rod(f"seat_grip_return_{k+1}_{side}", shoulder, grip_end, 0.014, material=blue, body=platform)
        v4.sphere(f"seat_grip_elbow_{k+1}_{side}", 0.014, shoulder, material=blue, body=platform)
        # Rubberized grip sleeve follows the bent return and terminates before the cap.
        sleeve_start = radial(0.32, theta, 0.625)
        sleeve_end = radial(0.338, theta, 0.648)
        v4.rod(f"grip_sleeve_{k+1}_{side}", sleeve_start, sleeve_end, 0.016, material=rubber, body=platform)
        v4.sphere(f"grip_end_cap_{k+1}_{side}", 0.014, grip_end, material=blue, body=platform)
        # Round mounting flange and two exposed bolts at the deck foot.
        v4.cylinder(f"handrail_mount_flange_{k+1}_{side}", 0.028, 0.008, radial(0.30, theta, 0.31),
                    bevel=0.002, material=steel, body=platform)
        for bolt_side in (-1, 1):
            bolt_theta = theta + bolt_side * 0.018 / 0.30
            fastener(f"handrail_mount_bolt_{k+1}_{side}_{bolt_side}", radial(0.30, bolt_theta, 0.316),
                     (0, 0, 1), 0.004, 0.004, steel, platform)
    # Cross handle across the top of the twin uprights.
    p0 = radial(0.34, a - 0.12 / 0.30, 0.65)
    p1 = radial(0.34, a + 0.12 / 0.30, 0.65)
    v4.rod(f"seat_cross_grip_{k+1}", p0, p1, 0.014, material=blue, body=platform)

v4.joint("platform_spin", "continuous", base, platform, origin=(0, 0, 0.478), axis=(0, 0, 1))

# Save the mechanically neutral pose.
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
