"""Product-quality articulated rechargeable toothbrush. Run with Blender background Python."""
import math
import os
import sys
import bpy
import bmesh
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials
shell = v4.plastic("porcelain_white_shell", (0.91, 0.93, 0.91), roughness=0.27, texture=0.08)
white_soft = v4.plastic("warm_white_head", (0.96, 0.96, 0.92), roughness=0.32, texture=0.06)
teal = v4.rubber("deep_teal_elastomer", (0.018, 0.12, 0.13))
charcoal = v4.plastic("graphite_trim", (0.045, 0.065, 0.07), roughness=0.3, texture=0.05)
steel = v4.metal("satin_champagne", (0.72, 0.58, 0.37), roughness=0.32, brushed=True)
chrome = v4.metal("soft_chrome", (0.72, 0.76, 0.78), roughness=0.25, brushed=False)
cyan = v4.emissive("cyan_status", (0.12, 0.78, 0.88), 1.8)
blue_bristle = v4.plastic("blue_nylon", (0.05, 0.38, 0.74), roughness=0.48, texture=0.02)
white_bristle = v4.plastic("white_nylon", (0.96, 0.95, 0.87), roughness=0.48, texture=0.02)
sea_bristle = v4.plastic("mint_nylon", (0.12, 0.68, 0.58), roughness=0.48, texture=0.02)

# Bodies: all handle-fixed details are part of the one grip assembly.
grip = v4.body("grip")
button = v4.body("power_button")
head = v4.body("brush_head")

def curved_pad(name, face, center_z=0.063, total_h=0.055, width=0.020, center_y=0.0, side=1):
    """Thin capsule pad whose back follows the rounded box handle cross-section."""
    r = width * 0.5
    straight_half = (total_h - width) * 0.5
    count_z, count_u = 81, 25
    verts, faces = [], []
    for iz in range(count_z):
        z = center_z - total_h * 0.5 + total_h * iz / (count_z - 1)
        dz = z - center_z
        cap_delta = max(0.0, abs(dz) - straight_half)
        half = math.sqrt(max(1e-10, r * r - cap_delta * cap_delta))
        for iu in range(count_u):
            u = -1.0 + 2.0 * iu / (count_u - 1)
            across = u * half
            if face == "front":
                x = across
                bevel_delta = max(0.0, abs(x) - 0.005)
                y = -0.0135 + 0.012 - math.sqrt(max(1e-10, 0.012**2 - bevel_delta**2))
                verts.append((x, y, z))
            else:
                y = center_y + across
                bevel_delta = max(0.0, abs(y) - 0.0015)
                x = side * (0.017 - 0.012 + math.sqrt(max(1e-10, 0.012**2 - bevel_delta**2)))
                verts.append((x, y, z))
    for iz in range(count_z - 1):
        for iu in range(count_u - 1):
            a = iz * count_u + iu
            quad = (a, a + 1, a + count_u + 1, a + count_u)
            faces.append(quad if face == "front" or side > 0 else tuple(reversed(quad)))
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    # Parameter order gives the patch outward-facing normals on each handle surface.
    obj = bpy.data.objects.new(name, mesh)
    v4._link(obj)
    v4.assign(obj, teal)
    for poly in mesh.polygons:
        poly.use_smooth = True
    solid = obj.modifiers.new("Pad thickness", "SOLIDIFY")
    solid.thickness = 0.00065
    solid.offset = 1.0
    edge = obj.modifiers.new("Soft pad edge", "BEVEL")
    edge.width = 0.00022
    edge.segments = 3
    v4.part(obj, grip)
    return obj

# Main handle: soft, tapered injection-moulded shell, standing on z=0.
handle = v4.box("handle_shell", (0.034, 0.027, 0.132), (0, 0, 0.074), bevel=0.012, material=shell, body=grip)
# Slightly narrower lower cap creates a realistic battery-door parting seam.
v4.box("battery_cap", (0.030, 0.024, 0.030), (0, 0, 0.022), bevel=0.010, material=shell, body=grip)
# Thin warm-metal band follows the lower cap edge as a subtle premium accent.
v4.torus("battery_seam_accent", 0.0132, 0.00065, loc=(0, 0, 0.037), material=steel, body=grip)
# Soft-touch front and side grip inlays follow the handle's rounded cross-section.
curved_pad("front_grip_inlay", "front")
for sx in (-1, 1):
    curved_pad(f"side_grip_{sx}", "side", center_z=0.062, width=0.015, center_y=0.001, side=sx)
# Moulded lines at the battery cap boundary.
v4.torus("cap_parting_line", 0.0135, 0.00035, loc=(0, 0, 0.0385), material=charcoal, body=grip)
# Small charging cradle contacts on the bottom face.
for x in (-0.0045, 0.0045):
    v4.cylinder(f"charging_contact_{x}", 0.0016, 0.0013, (x, 0, 0.00735), segments=24, bevel=0.00015,
                material=steel, body=grip)
# Rear charging indicator and subtle molded name on the front inlay.
v4.cylinder("rear_charge_port_rim", 0.0025, 0.0010, (0, 0.0138, 0.026), rot=(math.pi/2, 0, 0),
            bevel=0.00025, material=charcoal, body=grip)
v4.cylinder("rear_charge_port", 0.00125, 0.0012, (0, 0.0141, 0.026), rot=(math.pi/2, 0, 0),
            bevel=0.00015, material=steel, body=grip)

# Control island on the front: bezel and three status windows fixed to grip.
# Button pivot is at its lower edge; trim and cap form the movable button body.
button_z = 0.106
pivot = (0, -0.0128, 0.100)
# Ring bezel is fixed around the cap, with a slim edge reveal.
v4.sphere("button_bezel", 1.0, (0, -0.0142, button_z), material=charcoal, body=grip).scale = (0.0074, 0.0021, 0.0100)
v4.sphere("button_trim", 1.0, (0, -0.0157, button_z), material=steel, body=button).scale = (0.0063, 0.0011, 0.0087)
v4.sphere("button_cap", 1.0, (0, -0.0165, button_z), material=teal, body=button).scale = (0.0055, 0.0012, 0.0078)
# A tiny power glyph in raised silver, lying on the button's curved surface.
v4.cylinder("power_icon_dot", 0.00095, 0.00035, (0, -0.01765, button_z + 0.0005), rot=(math.pi/2, 0, 0),
            segments=24, bevel=0.0001, material=white_soft, body=button)
v4.torus("power_icon_arc", 0.0021, 0.00025, loc=(0, -0.01755, button_z + 0.0002), rot=(math.pi/2, 0, 0),
         material=white_soft, body=button)
# Three mode LEDs follow the lower handle center line.
for i, z in enumerate((0.084, 0.0795, 0.075)):
    v4.sphere(f"mode_led_{i}", 1.0, (0, -0.01415, z), material=cyan if i == 0 else chrome, body=grip).scale = (0.00115, 0.00055, 0.00115)
# Small restrained model mark follows the front grip inlay.
v4.text("grip_model_mark", "SONIC", 0.0032, loc=(0, -0.0135, 0.047), rot=(math.pi/2, 0, 0),
        material=white_soft, body=grip, on=bpy.data.objects["front_grip_inlay"])
# Fixed neck: a smooth, rounded loft flows from the handle shoulder into the drive shaft.
shoulder = v4.lathe("neck_shoulder", [(0, 0.132), (0.0170, 0.132), (0.0160, 0.135),
                                        (0.0143, 0.138), (0.0118, 0.141), (0.0090, 0.144),
                                        (0.0070, 0.148), (0.0057, 0.151), (0, 0.151)],
                    material=shell, body=grip)
shoulder.scale.y = 0.86
v4.torus("neck_accent_ring", 0.0062, 0.0007, loc=(0, 0, 0.151), material=steel, body=grip)
v4.cylinder("drive_shaft", 0.0057, 0.025, (0, 0, 0.1625), segments=40, bevel=0.0012, material=shell, body=grip)
# Fixed yoke cheeks and the visible transverse hinge pin at the drive-shaft end.
for sx in (-1, 1):
    v4.cylinder(f"hinge_yoke_{sx}", 0.0025, 0.0018, (sx * 0.0060, -0.0002, 0.174),
                rot=(0, math.pi/2, 0), segments=32, bevel=0.00025, material=charcoal, body=grip)
v4.cylinder("head_hinge_pin", 0.0014, 0.018, (0, -0.0002, 0.174), rot=(0, math.pi/2, 0),
            segments=32, bevel=0.00025, material=chrome, body=grip)
for sx in (-1, 1):
    v4.cylinder(f"hinge_pin_screw_{sx}", 0.0007, 0.0005, (sx * 0.00925, -0.0002, 0.174),
                rot=(0, math.pi/2, 0), segments=24, bevel=0.00010, material=chrome, body=grip)

# Movable oval head shell: elongated along the handle axis, bristles face forward (-Y).
v4.box("head_shell", (0.0132, 0.0084, 0.030), (0, -0.0006, 0.189), bevel=0.0056, material=white_soft, body=head)
# Narrow base tongue nests into the yoke at the hinge axis.
v4.box("head_hinge_tongue", (0.0080, 0.0060, 0.0080), (0, -0.0004, 0.176), bevel=0.0026, material=white_soft, body=head)
# Brush plate and dark elastomer gasket sit on the forward face of the head.
v4.box("head_gasket", (0.0116, 0.0010, 0.0255), (0, -0.00485, 0.190), bevel=0.0047, material=teal, body=head)
v4.box("bristle_plate", (0.0107, 0.0010, 0.0245), (0, -0.00575, 0.190), bevel=0.0042, material=white_soft, body=head)
# Soft edge ribs on the brush shell.
for sx in (-1, 1):
    v4.box(f"head_side_trim_{sx}", (0.0007, 0.0013, 0.020), (sx * 0.0065, -0.0015, 0.190), bevel=0.0003,
           material=teal, body=head)
# Fine nylon fibers in a dense, staggered oval field. Tuft counts taper toward the ends and row
# centers shift subtly, avoiding a rigid comb grid. Each cluster has fine tapered filaments and a
# slight height variation; all roots are embedded in the plate.
row_counts = (4, 5, 6, 6, 6, 6, 5, 4)
row_shifts = (0.0, 0.00045, -0.00025, 0.00060, -0.00045, 0.00030, -0.00050, 0.00020)
for row, count in enumerate(row_counts):
    z = 0.1804 + row * 0.00278
    pitch = 0.0078 / max(count - 1, 1)
    for col in range(count):
        x = -0.5 * pitch * (count - 1) + col * pitch + row_shifts[row]
        accent = (row in (0, 7) or (row in (1, 6) and col in (0, count - 1)))
        matl = blue_bristle if accent else (sea_bristle if (row * 3 + col * 2) % 7 == 0 else white_bristle)
        fiber_offsets = [(0.0, 0.0)]
        for k in range(5):
            a = math.tau * k / 5 + (row % 2) * math.pi / 5
            fiber_offsets.append((0.00020 * math.cos(a), 0.00020 * math.sin(a)))
        for k in range(5):
            a = math.tau * k / 5 + math.pi / 5 + (col % 2) * math.pi / 10
            fiber_offsets.append((0.00040 * math.cos(a), 0.00040 * math.sin(a)))
        tuft_height = 0.0098 + 0.0010 * (0.5 + 0.5 * math.sin(row * 1.7 + col * 2.3))
        for fiber, (dx, dz) in enumerate(fiber_offsets):
            length = tuft_height + 0.00012 * ((fiber % 3) - 1)
            root_y = -0.00570
            center_y = root_y - length * 0.5
            v4.cylinder(f"bristle_{row}_{col}_{fiber}", 0.00017, length,
                        (x + dx, center_y, z + dz), rot=(math.pi/2, 0, 0),
                        segments=10, bevel=0.00004, radius_top=0.00012,
                        material=matl, body=head)
# Small color accent at the tail of the brush head.
v4.sphere("head_identifier_dot", 1.0, (0, -0.00635, 0.201), material=cyan, body=head).scale = (0.0011, 0.00035, 0.0011)

# Two real independent motions, each constrained to a limited, plausible travel range.
v4.joint("button_press", "revolute", grip, button, origin=pivot, axis=(1, 0, 0),
         limits=(-math.radians(12), 0.0))
v4.joint("head_hinge", "revolute", grip, head, origin=(0, -0.0002, 0.174), axis=(1, 0, 0),
         limits=(-math.radians(12), math.radians(12)))

v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
