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

v4.reset()
# Materials
yellow = v4.plastic("safety_yellow", (0.94, 0.58, 0.035), roughness=0.31)
yellow_hi = v4.plastic("yellow_detail", (1.0, 0.70, 0.075), roughness=0.32)
black = v4.plastic("charcoal_polymer", (0.045, 0.052, 0.056), roughness=0.43)
rubber = v4.rubber("grip_rubber", (0.025, 0.029, 0.031))
metal = v4.metal("cast_aluminum", color=(0.48, 0.50, 0.51), roughness=0.38, brushed=False)
steel = v4.metal("stainless_steel", color=(0.72, 0.74, 0.75), roughness=0.27, brushed=True)
guardmat = v4.metal("pressed_guard_steel", color=(0.54, 0.57, 0.58), roughness=0.32, brushed=True)
discmat = v4.mat("abrasive_composite", (0.11, 0.12, 0.13), roughness=0.82)
labelmat = v4.mat("warm_silver_label", (0.78, 0.78, 0.72), roughness=0.45)
white = v4.mat("marking_ink", (0.94, 0.93, 0.84), roughness=0.6)

housing = v4.body("housing")
switch = v4.body("switch")
guard = v4.body("guard")
disc = v4.body("disc")

# Coordinates: motor runs rear (-X) to the cast gearcase (+X); the spindle points down along -Z.
CX, DZ = 0.125, 0.075
HEAD_CX, HEAD_Z = 0.101, 0.112
# Main motor barrel and stepped end caps, all details touching/overlapping as molded features.
v4.cylinder("motor_barrel", 0.036, 0.185, (-0.0725, 0, 0.112), rot=(0, math.pi/2, 0), radius_top=0.032, bevel=0.004, material=yellow, body=housing)
v4.cylinder("rear_end_cap", 0.034, 0.020, (-0.175, 0, 0.112), rot=(0, math.pi/2, 0), bevel=0.003, material=black, body=housing)
v4.cylinder("rear_cap_lip", 0.036, 0.006, (-0.165, 0, 0.112), rot=(0, math.pi/2, 0), bevel=0.001, material=yellow_hi, body=housing)
# Front motor collar, gearbox neck, and squat cast-aluminium right-angle gearcase.
v4.cylinder("front_motor_collar", 0.034, 0.020, (0.030, 0, 0.112), rot=(0, math.pi/2, 0), bevel=0.002, material=black, body=housing)
v4.cylinder("gear_neck", 0.023, 0.061, (0.070, 0, 0.112), rot=(0, math.pi/2, 0), bevel=0.002, material=metal, body=housing)
def rounded_casting(name, levels, exponent=3.4, segments=48):
    verts=[]; faces=[]
    for z,rx,ry in levels:
        for i in range(segments):
            a=math.tau*i/segments; c,s=math.cos(a),math.sin(a)
            verts.append((HEAD_CX+rx*math.copysign(abs(c)**(2/exponent),c),
                          ry*math.copysign(abs(s)**(2/exponent),s),z))
    for layer in range(len(levels)-1):
        for i in range(segments):
            a=layer*segments+i; b=layer*segments+(i+1)%segments
            faces.append((a,b,b+segments,a+segments))
    faces.append(tuple(range(segments-1,-1,-1)))
    faces.append(tuple((len(levels)-1)*segments+i for i in range(segments)))
    me=bpy.data.meshes.new(name+"Mesh"); me.from_pydata(verts,[],faces); me.materials.append(metal); me.update()
    for poly in me.polygons:
        poly.use_smooth = len(poly.vertices)==4
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); v4.part(ob,housing)
    bevel=ob.modifiers.new("soft_cast_edges","BEVEL"); bevel.width=0.0012; bevel.segments=3
    return ob
rounded_casting("gearcase_bulge",[(0.0895,0.021,0.020),(0.092,0.028,0.026),(0.100,0.030,0.0275),
                                   (0.122,0.030,0.0275),(0.131,0.027,0.025),(0.1345,0.024,0.022)])
# Low rectangular inspection covers and perimeter screws on the two cast sides.
for sy in (-1, 1):
    v4.box(f"gear_cover_{sy}",(0.032,0.003,0.024),(HEAD_CX,sy*0.0285,HEAD_Z),bevel=0.002,material=steel,body=housing)
    for ix in (-1,1):
        for iz in (-1,1):
            v4.cylinder(f"gear_screw_{sy}_{ix}_{iz}",0.0023,0.0018,
                        (HEAD_CX+ix*0.012,sy*0.0303,HEAD_Z+iz*0.008),
                        rot=(math.pi/2,0,0),segments=16,bevel=0.0003,material=metal,body=housing)
# A vent grille on each cast cheek and a second threaded auxiliary-handle socket.
for sy in (-1, 1):
    for i in range(4):
        v4.box(f"gear_vent_{sy}_{i}",(0.0022,0.0012,0.009),(HEAD_CX-0.009+i*0.006,sy*0.0304,HEAD_Z-0.002),
               rot=(0,0,math.radians(18)),bevel=0.0007,material=black,body=housing)
    v4.cylinder(f"opposite_handle_socket_{sy}",0.008,0.004,(0.094,sy*0.030,0.112),
                rot=(math.pi/2,0,0),bevel=0.0008,material=black,body=housing)
    v4.cylinder(f"opposite_handle_thread_{sy}",0.0058,0.004,(0.094,sy*0.034,0.112),
                rot=(math.pi/2,0,0),bevel=0.0004,material=steel,body=housing)
# Removable 90 mm auxiliary handle: threaded steel neck and ribbed black grip.
v4.cylinder("side_handle_mount_boss",0.012,0.008,(0.094,0.0305,0.112),rot=(math.pi/2,0,0),bevel=0.001,material=steel,body=housing)
v4.cylinder("side_handle_threaded_stem",0.006,0.018,(0.094,0.0435,0.112),rot=(math.pi/2,0,0),bevel=0.0006,material=metal,body=housing)
for i in range(5):
    v4.torus(f"handle_thread_{i}",0.0062,0.00055,(0.094,0.037+i*0.0025,0.112),rot=(math.pi/2,0,0),material=steel,body=housing)
v4.cylinder("auxiliary_handle_grip",0.0105,0.090,(0.094,0.0975,0.112),rot=(math.pi/2,0,0),bevel=0.002,material=black,body=housing)
for i in range(9):
    v4.torus(f"handle_grip_rib_{i}",0.0099,0.0010,(0.094,0.056+i*0.009,0.112),rot=(math.pi/2,0,0),material=rubber,body=housing)
v4.cylinder("auxiliary_handle_endcap",0.0105,0.006,(0.094,0.143,0.112),rot=(math.pi/2,0,0),bevel=0.0015,material=black,body=housing)
# Annular bearing boss under the gearcase: the central bore clears the rotating spindle.
def annulus_mesh(name, center, inner_r, outer_r, depth, material, bodyref, segments=64):
    x0,y0,z0=center; verts=[]; faces=[]
    # XY annulus with its axis along Z.
    for z in (z0-depth/2,z0+depth/2):
        for r in (inner_r,outer_r):
            for i in range(segments):
                a=math.tau*i/segments
                verts.append((x0+r*math.cos(a),y0+r*math.sin(a),z))
    def ix(layer,ring,i): return layer*2*segments+ring*segments+(i%segments)
    for i in range(segments):
        j=(i+1)%segments
        faces.extend([(ix(0,0,i),ix(0,0,j),ix(0,1,j),ix(0,1,i)),
                      (ix(1,0,i),ix(1,1,i),ix(1,1,j),ix(1,0,j)),
                      (ix(0,0,i),ix(1,0,i),ix(1,0,j),ix(0,0,j)),
                      (ix(0,1,i),ix(0,1,j),ix(1,1,j),ix(1,1,i))])
    me=bpy.data.meshes.new(name+"Mesh"); me.from_pydata(verts,[],faces); me.materials.append(material); me.update()
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); v4.part(ob,bodyref); return ob
annulus_mesh("downward_spindle_boss",(CX,0,0.0845),0.008,0.014,0.011,metal,housing)
# Spindle lock button is retained on the flat top of the case (small orange pin).
v4.cylinder("lock_socket",0.010,0.006,(0.100,0,0.137),bevel=0.001,material=black,body=housing)
v4.cylinder("spindle_lock",0.007,0.010,(0.100,0,0.145),bevel=0.002,material=yellow_hi,body=housing)
for i,xfin in enumerate((0.075,0.084)):
    v4.box(f"gearcase_cooling_fin_{i}",(0.004,0.034,0.002),(xfin,0,0.134),bevel=0.0008,material=steel,body=housing)

# Molded dark rear grip sleeve with circumferential ribs and shallow grip pads.
v4.cylinder("rear_grip_sleeve", 0.038, 0.080, (-0.124, 0, 0.112), rot=(0, math.pi/2, 0), bevel=0.002, material=rubber, body=housing)
for i in range(8):
    x = -0.159 + i*0.010
    v4.torus(f"grip_rib_{i}", 0.0374, 0.0010, (x,0,0.112), rot=(0,math.pi/2,0), material=black, body=housing)
# Side grip panels with raised chevrons on both sides.
for sy in (-1,1):
    v4.box(f"grip_panel_{sy}", (0.066,0.003,0.048), (-0.119,sy*0.0375,0.112), bevel=0.006, material=black, body=housing)
    for k in range(4):
        v4.rod(f"grip_groove_{sy}_{k}",(-0.145+k*0.014,sy*0.039,0.095),(-0.134+k*0.014,sy*0.039,0.129),0.0014,material=rubber,body=housing)
# Cooling vents: dark slots on both sides, placed over shell in a compact row.
for sy in (-1,1):
    for i in range(7):
        x = -0.015 - i*0.009
        v4.box(f"vent_slot_{sy}_{i}",(0.004,0.0018,0.021), (x,sy*0.0337,0.112), rot=(0,0,math.radians(-16)), bevel=0.0015, material=black, body=housing)
# Small yellow molded seam strips at motor shell shoulder.
for x in (-0.033, 0.004):
    v4.torus(f"shell_seam_{x}",0.034 if x < 0 else 0.033,0.0010,(x,0,0.112),rot=(0,math.pi/2,0),material=yellow_hi,body=housing)
# Side specification badge on both sides, printed product markings.
for sy, rot in [(-1,(math.pi/2,0,0)),(1,(-math.pi/2,0,math.pi))]:
    v4.box(f"rating_badge_{sy}",(0.056,0.0015,0.022),(-0.045,sy*0.0368,0.112),bevel=0.002,material=black,body=housing)
    v4.text(f"brand_mark_{sy}","VOLTEX",0.008,loc=(-0.069,sy*0.0378,0.116),rot=rot,extrude_depth=0.00035,material=white,body=housing)
    v4.text(f"spec_mark_{sy}","125 mm  |  900 W",0.0038,loc=(-0.069,sy*0.0378,0.108),rot=rot,extrude_depth=0.0002,material=labelmat,body=housing)
# Rear cap slots and cable strain relief extending from the back.
for i in range(5):
    y=-0.024+i*0.012
    v4.box(f"rear_cap_vent_{i}",(0.0018,0.004,0.017),(-0.1855,y,0.112),bevel=0.001,material=black,body=housing)
def cable_mesh(points,radii,segments=16):
    from mathutils import Vector
    verts=[]; faces=[]; up=Vector((0,1,0)); pts=[Vector(p) for p in points]
    for i,p in enumerate(pts):
        tangent=(pts[min(i+1,len(pts)-1)]-pts[max(i-1,0)]).normalized()
        u=tangent.cross(up).normalized(); v=tangent.cross(u).normalized()
        for k in range(segments):
            a=math.tau*k/segments; q=p+radii[i]*(math.cos(a)*u+math.sin(a)*v); verts.append(tuple(q))
    for i in range(len(pts)-1):
        for k in range(segments):
            a=i*segments+k; b=i*segments+(k+1)%segments
            faces.append((a,b,b+segments,a+segments))
    faces.extend([tuple(range(segments-1,-1,-1)),tuple((len(pts)-1)*segments+k for k in range(segments))])
    me=bpy.data.meshes.new("power_cable_mesh"); me.from_pydata(verts,[],faces); me.materials.append(black); me.materials.append(rubber); me.update()
    # The enlarged first 40 mm are a tapered molded rubber strain relief.
    for poly in me.polygons:
        poly.material_index = 1 if poly.index < 4*segments else 0
    ob=bpy.data.objects.new("power_cable",me); bpy.context.collection.objects.link(ob); v4.part(ob,housing)
cable_mesh([(-0.176,0,0.112),(-0.183,0,0.112),(-0.190,0,0.112),(-0.198,0,0.112),(-0.208,0,0.112),(-0.220,0,0.111),(-0.232,0,0.108),(-0.244,0,0.101),(-0.255,0,0.090),(-0.266,0,0.076),(-0.276,0,0.063),(-0.286,0,0.060)],[0.011,0.011,0.0105,0.009,0.006,0.006,0.006,0.006,0.006,0.006,0.006,0.006])
# Shallow circumferential bellows ridges make the molded 40 mm strain relief legible.
for i, (x, r) in enumerate(((-0.180,0.0108),(-0.187,0.0105),(-0.194,0.0099),(-0.201,0.0088))):
    v4.torus(f"strain_relief_rib_{i}",r,0.0008,(x,0,0.112),rot=(0,math.pi/2,0),material=rubber,body=housing)
# Cable ends short, keeps asset compact, visible as exiting tool cable.

# Long, low profile paddle switch seated along the motor crown, with a shallow raised bezel.
v4.cylinder("switch_hinge_barrel",0.0075,0.038,(-0.066,0,0.153),rot=(math.pi/2,0,0),material=steel,body=switch)
v4.box("trigger_paddle",(0.050,0.018,0.003),(-0.091,0,0.154),rot=(0,0,0),bevel=0.008,material=black,body=switch)
v4.box("trigger_thumb_pad",(0.039,0.013,0.0015),(-0.093,0,0.1562),bevel=0.006,material=rubber,body=switch)
for i in range(6):
    v4.box(f"trigger_ridge_{i}",(0.0014,0.009,0.0006),(-0.109+i*0.006,0,0.157),bevel=0.0003,material=black,body=switch)
# Recess-like seat on the crown, with a narrow yellow perimeter that follows the shell.
v4.box("switch_recess_seat",(0.060,0.022,0.002),(-0.091,0,0.147),bevel=0.007,material=black,body=housing)
v4.box("switch_seat_inlay",(0.052,0.018,0.001),(-0.091,0,0.148),bevel=0.006,material=yellow_hi,body=housing)
# Fixed hinge bosses/pins on housing flank.
for sy in (-1,1):
    v4.cylinder(f"switch_pivot_cap_{sy}",0.010,0.003,(-0.066,sy*0.017,0.153),rot=(math.pi/2,0,0),material=yellow_hi,body=housing)

# Wheel rotates in a horizontal XY plane on the downward Z spindle.
def lathed_disc_profile(name, profile, material, bodyref, segments=96):
    verts=[]; faces=[]
    for k in range(segments):
        a=math.tau*k/segments
        for r,z in profile: verts.append((CX+r*math.cos(a),r*math.sin(a),z))
    m=len(profile)
    for k in range(segments):
        kn=(k+1)%segments
        for j in range(m): faces.append((k*m+j,kn*m+j,kn*m+(j+1)%m,k*m+(j+1)%m))
    me=bpy.data.meshes.new(name+"Mesh"); me.from_pydata(verts,[],faces); me.materials.append(material); me.update()
    for p in me.polygons: p.use_smooth=True
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); v4.part(ob,bodyref); return ob
# Bevelled outer rim with a depressed dish and a raised central shoulder around the arbor.
lathed_disc_profile("abrasive_disc",[(0.061,0.073),(0.061,0.077),(0.056,0.077),(0.024,0.073),
                                     (0.018,0.078),(0.009,0.078),(0.009,0.074),(0.017,0.074),
                                     (0.024,0.069),(0.056,0.073)],discmat,disc)
# Fine grit bump gives the abrasive face a subtle mineral texture at close range.
nt=discmat.node_tree; bsdf=nt.nodes.get("Principled BSDF")
noise=nt.nodes.new("ShaderNodeTexNoise"); noise.inputs["Scale"].default_value=420; noise.inputs["Detail"].default_value=2
bump=nt.nodes.new("ShaderNodeBump"); bump.inputs["Strength"].default_value=0.13; bump.inputs["Distance"].default_value=0.00025
nt.links.new(noise.outputs["Fac"],bump.inputs["Height"]); nt.links.new(bump.outputs["Normal"],bsdf.inputs["Normal"])
annulus_mesh("disc_reinforced_hub",(CX,0,0.0795),0.0075,0.017,0.003,labelmat,disc,64)
# Rotor spindle sits inside the annular bearing boss and wheel bore with running clearance.
v4.cylinder("spindle_shaft",0.007,0.010,(CX,0,0.082),bevel=0.0006,material=steel,body=disc)
# Visible outer flange nut with two flush dark pin holes.
annulus_mesh("outer_clamp_flange",(CX,0,0.0825),0.0074,0.0145,0.003,steel,disc,64)
for side in (-1,1):
    v4.cylinder(f"flange_pin_hole_{side}",0.0016,0.0004,(CX+side*0.0105,0,0.0838),bevel=0,material=black,body=disc)
annulus_mesh("locking_nut",(CX,0,0.0725),0.0073,0.0105,0.003,metal,disc,48)
# Printed label ring and small safety mark follow the shallow outer dish.
v4.torus("disc_printed_ring",0.049,0.00065,(CX,0,0.0763),material=labelmat,body=disc)
v4.text("disc_label","A 60 T",0.005,loc=(CX-0.025,-0.004,0.0735),rot=(0,0,0),extrude_depth=0.0002,material=white,body=disc)

# Pressed guard is a horizontal half-shroud over the rear/operator (-X) half of the wheel.
def guard_sector_mesh():
    n=64; z0,z1=DZ-0.006,DZ+0.006; ri,ro=0.063,0.075
    verts=[]; faces=[]
    # two axial faces, inner/outer radii, and a rear semicircle from +Y through -X to -Y
    def idx(zi,ri_idx,i): return zi*2*(n+1)+ri_idx*(n+1)+i
    for z in (z0,z1):
        for r in (ri,ro):
            for i in range(n+1):
                a=math.pi/2 + math.pi*i/n
                verts.append((CX+r*math.cos(a),r*math.sin(a),z))
    for i in range(n):
        faces.append((idx(0,0,i),idx(0,0,i+1),idx(0,1,i+1),idx(0,1,i)))
        faces.append((idx(1,0,i),idx(1,1,i),idx(1,1,i+1),idx(1,0,i+1)))
        faces.append((idx(0,0,i),idx(1,0,i),idx(1,0,i+1),idx(0,0,i+1)))
        faces.append((idx(0,1,i),idx(0,1,i+1),idx(1,1,i+1),idx(1,1,i)))
    for i in (0,n): faces.append((idx(0,0,i),idx(0,1,i),idx(1,1,i),idx(1,0,i)))
    mesh=bpy.data.meshes.new("guard_shell_mesh"); mesh.from_pydata(verts,[],faces); mesh.materials.append(guardmat); mesh.update()
    obj=bpy.data.objects.new("pressed_guard_shell",mesh); bpy.context.collection.objects.link(obj); v4.part(obj,guard)

guard_sector_mesh()
# Flat pressed top plate shields the rear half of the wheel, joining the rolled rim.
def guard_top_plate_mesh():
    n=64; z0,z1=0.079,0.081; ri,ro=0.023,0.076
    verts=[]; faces=[]
    def idx(zi,ri_idx,i): return zi*2*(n+1)+ri_idx*(n+1)+i
    for z in (z0,z1):
        for r in (ri,ro):
            for i in range(n+1):
                a=math.pi/2 + math.pi*i/n
                verts.append((CX+r*math.cos(a),r*math.sin(a),z))
    for i in range(n):
        faces.extend([(idx(0,0,i),idx(0,0,i+1),idx(0,1,i+1),idx(0,1,i)),
                      (idx(1,0,i),idx(1,1,i),idx(1,1,i+1),idx(1,0,i+1)),
                      (idx(0,0,i),idx(1,0,i),idx(1,0,i+1),idx(0,0,i+1)),
                      (idx(0,1,i),idx(0,1,i+1),idx(1,1,i+1),idx(1,1,i))])
    for i in (0,n): faces.append((idx(0,0,i),idx(0,1,i),idx(1,1,i),idx(1,0,i)))
    me=bpy.data.meshes.new("guard_top_plate_mesh"); me.from_pydata(verts,[],faces); me.materials.append(guardmat); me.update()
    ob=bpy.data.objects.new("rear_half_disc_cover",me); bpy.context.collection.objects.link(ob); v4.part(ob,guard)
guard_top_plate_mesh()
# Rolled operator-side skirt drops below the wheel perimeter while clearing the disc by 2 mm.
def guard_lip_mesh():
    n=64; z0,z1=DZ-0.017,DZ-0.005; ri,ro=0.063,0.075
    verts=[]; faces=[]
    def idx(zi,ri_idx,i): return zi*2*(n+1)+ri_idx*(n+1)+i
    for z in (z0,z1):
        for r in (ri,ro):
            for i in range(n+1):
                a=math.pi/2 + math.pi*i/n
                verts.append((CX+r*math.cos(a),r*math.sin(a),z))
    for i in range(n):
        faces.extend([(idx(0,0,i),idx(0,0,i+1),idx(0,1,i+1),idx(0,1,i)),
                      (idx(1,0,i),idx(1,1,i),idx(1,1,i+1),idx(1,0,i+1)),
                      (idx(0,0,i),idx(1,0,i),idx(1,0,i+1),idx(0,0,i+1)),
                      (idx(0,1,i),idx(0,1,i+1),idx(1,1,i+1),idx(1,1,i))])
    for i in (0,n): faces.append((idx(0,0,i),idx(0,1,i),idx(1,1,i),idx(1,0,i)))
    me=bpy.data.meshes.new("guard_lip_mesh"); me.from_pydata(verts,[],faces); me.materials.append(guardmat); me.update()
    ob=bpy.data.objects.new("operator_side_guard_lip",me); bpy.context.collection.objects.link(ob); v4.part(ob,guard)
guard_lip_mesh()
# Wide split clamp band surrounds the 14 mm spindle boss with 1.5 mm radial clearance.
annulus_mesh("guard_clamp_band",(CX,0,DZ+0.008),0.0155,0.021,0.009,guardmat,guard,64)
# Formed bridge ties the band to the rear shroud; a cross-bolt closes the band split.
v4.rod("guard_clamp_bridge",(CX-0.020,0,DZ+0.011),(CX-0.063,0,DZ+0.011),0.0015,material=guardmat,body=guard)
v4.rod("guard_bridge_outer_stay",(CX-0.063,0,DZ+0.006),(CX-0.063,0,DZ+0.011),0.002,material=guardmat,body=guard)
v4.box("guard_clamp_lug",(0.014,0.020,0.010),(CX+0.023,0,DZ+0.008),bevel=0.0015,material=guardmat,body=guard)
v4.cylinder("guard_clamp_bolt",0.0035,0.024,(CX+0.023,0,DZ+0.008),rot=(math.pi/2,0,0),bevel=0.0007,material=steel,body=guard)
v4.cylinder("guard_adjust_knob",0.006,0.004,(CX+0.023,0.014,DZ+0.008),rot=(math.pi/2,0,0),bevel=0.001,material=black,body=guard)

# Retained joints, all rest at zero.
v4.joint("switch_hinge","revolute",housing,switch,origin=(-0.066,0,0.153),axis=(0,1,0),limits=(-math.radians(8),math.radians(24)))
v4.joint("guard_adjust","revolute",housing,guard,origin=(CX,0,DZ),axis=(0,0,1),limits=(-math.radians(55),math.radians(55)))
v4.joint("disc_spin","continuous",housing,disc,origin=(CX,0,DZ),axis=(0,0,1))

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