import math, os, sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4
from mathutils import Matrix
from mathutils.bvhtree import BVHTree

v4.reset()
# Materials
orange = v4.plastic('safety_orange_ABS', (0.92, 0.20, 0.025), roughness=0.31, texture=0.08)
orange_dark = v4.plastic('orange_recess', (0.38, 0.065, 0.012), roughness=0.4)
black = v4.rubber('charcoal_grip', (0.035, 0.042, 0.045))
roller_mat = v4.rubber('roller_rubber', (0.10, 0.115, 0.12))
steel = v4.metal('brushed_steel', (0.70, 0.72, 0.74), roughness=0.28)
bright_steel = v4.metal('blade_edge', (0.86, 0.88, 0.89), roughness=0.21, brushed=False)
core_mat = v4.mat('paper_core', (0.72, 0.59, 0.38), roughness=0.68)
tape = v4.plastic('amber_tape', (0.84, 0.48, 0.12), roughness=0.28, texture=0.025)
wind_tape = v4.plastic('wound_tape_edge', (0.79, 0.43, 0.095), roughness=0.34, texture=0.045)
ink = v4.mat('label_ink', (0.98, 0.82, 0.40), roughness=0.55)

# Dimensions and named bodies
frame = v4.body('frame')
roll = v4.body('tape_roll')
arm = v4.body('applicator_arm')
press = v4.body('pressure_roller')
blade = v4.body('cutter_blade')

# Profile-prism helper: outline points are world (Y,Z); extrude across X.
def side_plate(name, outline, x0, width, material, body, bevel=0.0015):
    o = v4.extrude(name, outline, width, loc=(x0,0,0), bevel=bevel, material=material, body=body)
    # Extrude's local (x,y,z) maps to world (Y,Z,X).
    o.data.transform(Matrix(((0,0,1,0),(1,0,0,0),(0,1,0,0),(0,0,0,1))))
    o.location = (x0,0,0)
    return o

def x_cylinder(name, radius, depth, loc, material, body, bevel=0.0006, segments=48):
    return v4.cylinder(name, radius, depth, loc, rot=(0,math.pi/2,0), segments=segments, bevel=bevel, material=material, body=body)

def x_torus(name, major, minor, loc, material, body):
    return v4.torus(name, major, minor, loc, rot=(0,math.pi/2,0), material=material, body=body)

# ---- Frame: open side cheeks around the roll, molded bridges, handle and nose ---------
# Same structural silhouette on both sides. The large clearance hole exposes the roll.
outline = [(-0.151,0.050),(-0.146,0.086),(-0.119,0.111),(-0.062,0.137),
           (0.004,0.158),(0.079,0.148),(0.112,0.124),(0.122,0.080),
           (0.120,0.038),(0.101,0.018),(0.072,0.017),(0.039,0.047),
           (0.008,0.054),(-0.025,0.035),(-0.068,0.019),(-0.112,0.030),(-0.139,0.047)]
for side, x in [('L',-0.035),('R',0.028)]:
    plate = side_plate('cheek_'+side, outline, x, 0.007, orange, frame, 0.002)
    cutter = v4.cylinder('temporary_roll_clearance', 0.057, 0.02, (x+0.0035,0.045,0.116),
                         rot=(0,math.pi/2,0), bevel=0, material=None)
    v4.boolean(plate,cutter)
    # Open a rounded hand-clearance notch below/behind the roll so the real grip is visible.
    grip_cut = v4.cylinder('temporary_grip_clearance',0.034,0.020,(x+0.0035,0.085,0.061),rot=(0,math.pi/2,0),bevel=0,material=None,segments=48)
    v4.boolean(plate,grip_cut)
    # Larger nose-side aperture exposes the pressure arm and application roller.
    arm_cut = v4.cylinder('temporary_arm_aperture',0.052,0.020,(x+0.0035,-0.0935,0.041),rot=(0,math.pi/2,0),bevel=0,material=None,segments=64)
    v4.boolean(plate,arm_cut)
    # A long rounded relief slot follows the arm and opens the broad forward web.
    web_cut = v4.box('temporary_web_slot',(0.020,0.074,0.018),(x+0.0035,-0.067,0.111),rot=(math.radians(42),0,0),bevel=0.008,material=None)
    v4.boolean(plate,web_cut)
# Thick bridge ribs at top/rear and beneath roll; molded frame gives side plates rigidity.
v4.box('upper_cross_bridge',(0.074,0.105,0.009),(0,0.025,0.154),bevel=0.003,material=orange,body=frame)
v4.box('lower_cross_bridge',(0.074,0.090,0.010),(0,0.035,0.025),bevel=0.003,material=orange,body=frame)
v4.box('nose_cross_bridge',(0.074,0.030,0.012),(0,-0.132,0.080),bevel=0.003,material=orange,body=frame)
# Fixed steel core spindle, hub collars and small brake shoe bearing on the core.
x_cylinder('core_spindle',0.009,0.061,(0,0.045,0.116),steel,frame,0.0004)
x_cylinder('hub_flange_left',0.017,0.003,(-0.030,0.045,0.116),steel,frame)
x_cylinder('hub_flange_right',0.017,0.003,(0.030,0.045,0.116),steel,frame)
# Fixed rubber friction shoe lightly bears on the core liner to brake, not lock, the roll.
v4.sphere('core_brake_shoe',0.006,(0,0.059,0.116),material=black,body=frame)
# Fixed tape path idler / guide roller just ahead of the roll.
x_cylinder('tape_guide_axle',0.004,0.060,(-0.001,-0.029,0.082),steel,frame,0.0003)
x_cylinder('tape_guide_drum',0.012,0.052,(0,-0.029,0.082),roller_mat,frame,0.001)
x_cylinder('guide_cap_L',0.006,0.002,(-0.027,-0.029,0.082),steel,frame)
x_cylinder('guide_cap_R',0.006,0.002,(0.027,-0.029,0.082),steel,frame)
# Handle: structural neck and separate rubber grip, with molded ribs and flared end caps.
v4.rod('handle_neck',(0,0.078,0.079),(0,0.126,0.025),0.014,material=orange,body=frame)
v4.rod('handle_grip',(0,0.080,0.075),(0,0.124,0.027),0.0155,material=black,body=frame)
# Grip bands are small collars wrapped around the diagonal grip axis.
for k in range(6):
    t=0.18+k*0.125
    cy=0.080+(0.124-0.080)*t; cz=0.075+(0.027-0.075)*t
    # torus default axis z; orient along diagonal handle direction
    v4.torus('grip_rib_%02d'%k,0.0151,0.0009,(0,cy,cz),rot=(math.radians(222.5),0,0),segments=32,ring_segments=10,material=roller_mat,body=frame)
# Rear palm stop and lower heel.
v4.sphere('palm_stop',0.014,(0,0.126,0.024),material=orange,body=frame)
# Two cross-ties anchor the central grip/neck to the structural side cheeks.
for yy,zz in ((0.080,0.075),(0.119,0.031)):
    v4.rod('handle_mount_tie_'+str(yy),(-0.035,yy,zz),(0.035,yy,zz),0.004,material=orange,body=frame)
# Raised top thumb pad, textured with transverse grooves.
v4.box('thumb_rest',(0.043,0.055,0.007),(0,0.043,0.163),bevel=0.003,material=black,body=frame)
for k in range(5):
    v4.box('thumb_groove_%d'%k,(0.039,0.0014,0.001),(0,0.023+k*0.009,0.167),bevel=0.0004,material=roller_mat,body=frame)
# Steel nose bracket, side mounting ears, and two visible rivets.
for sx in (-1,1):
    x_cylinder('nose_rivet_'+str(sx),0.0032,0.002,(sx*0.032,-0.132,0.080),steel,frame,0.0003,24)
v4.box('cutter_mount_plate',(0.056,0.010,0.006),(0,-0.134,0.067),bevel=0.001,material=steel,body=frame)
# Side cheek recessed styling and fasteners, placed on outer faces.

for sx in (-1,1):
    face_x=sx*0.039
    # Small round axle medallions at the exposed hub, with radial molded spokes.
    x_cylinder('hub_outer_cap_'+str(sx),0.014,0.002,(sx*0.030,0.045,0.116),orange_dark,frame,0.0004)
    x_cylinder('hub_center_button_'+str(sx),0.006,0.002,(sx*0.032,0.045,0.116),steel,frame,0.0005)
    for j in range(4):
        a=j*math.pi/2
        y=0.045+0.010*math.cos(a); z=0.116+0.010*math.sin(a)
        x_cylinder('hub_spoke_%s_%d'%(sx,j),0.0008,0.0016,(sx*0.033,y,z),ink,frame,0,12)
# Hub support spokes sit outboard of the roll and tie the fixed core to the side frame.
for j in range(3):
    a=j*2*math.pi/3
    y0,z0=0.045+0.012*math.cos(a),0.116+0.012*math.sin(a)
    y1,z1=0.045+0.054*math.cos(a),0.116+0.054*math.sin(a)
    v4.rod('hub_support_spoke_%d'%j,(0.036,y0,z0),(0.036,y1,z1),0.0015,material=orange_dark,body=frame)
# Coherent axle keeper: concentric washer, retaining ring and a slotted adjustment screw.
x_cylinder('axle_retainer_washer',0.013,0.004,(0.0385,0.045,0.116),steel,frame,0.0005)
x_torus('retainer_rim',0.0115,0.0012,(0.041,0.045,0.116),orange_dark,frame)
x_cylinder('brake_adjuster',0.0045,0.003,(0.042,0.045,0.116),steel,frame,0.0004,32)
x_cylinder('adjuster_lock_screw',0.0014,0.001,(0.044,0.045,0.116),orange_dark,frame,0,16)
# Three recessed cooling/grip slots break up the cheek's broad moulded surface.
for k in range(3):
    v4.box('cheek_vent_%d'%k,(0.0012,0.014,0.0024),(0.0354,-0.055+k*0.020,0.137),bevel=0.001,material=orange_dark,body=frame)
# Tape path arrows and simple product badge on visible outer side.
# Badge is a thin plate mounted on the right cheek's forward open area.
v4.box('badge_inset',(0.0012,0.033,0.010),(0.0354,-0.119,0.099),bevel=0.002,material=orange_dark,body=frame)
# Text with local +Z facing outward from X-positive face.
# Label is small enough to stay on cheek face; an embossed tape path indicator near nose.

# ---- Tape roll: annular solid strip on the fixed hub, continuous spin about X ---------
# Ring profile is made as a cylinder with a true core opening using boolean subtraction.
roll_outer = v4.cylinder('tape_roll_blank',0.052,0.048,(0,0.045,0.116),rot=(0,math.pi/2,0),bevel=0.0005,material=tape,body=roll,segments=96)
hole = v4.cylinder('temporary_core_hole',0.019,0.060,(0,0.045,0.116),rot=(0,math.pi/2,0),bevel=0,material=None,segments=64)
v4.boolean(roll_outer,hole)
# Off-white wound tape edge band on the near side; the label face ring makes the core readable.
x_torus('tape_edge_band',0.0355,0.0024,(-0.022,0.045,0.116),ink,roll)
x_torus('paper_core_lip_near',0.0146,0.0020,(-0.022,0.045,0.116),core_mat,roll)
x_torus('paper_core_lip_far',0.0146,0.0020,(0.022,0.045,0.116),core_mat,roll)
# Fine concentric winding lines catch light on the exposed tape circumference.
for i,rad in enumerate((0.0472,0.0490,0.0508)):
    x_torus('winding_line_%02d'%i,rad,0.00038,(0,0.045,0.116),wind_tape,roll)
# Layer edges on the tape-facing cheek are fine and nearly flush, like wound stock.
for i,rad in enumerate((0.039,0.042,0.045,0.048,0.051)):
    x_torus('tape_winding_face_line_%02d'%i,rad,0.00065,(-0.0237,0.045,0.116),wind_tape,roll)
sleeve=x_cylinder('paper_core_sleeve',0.019,0.046,(0,0.045,0.116),core_mat,roll,0.0004,64)
# Open core sleeve by fitting the roll's inner opening with a smaller insert; center bore stays clear.
inner_hole=v4.cylinder('temporary_sleeve_bore',0.010,0.060,(0,0.045,0.116),rot=(0,math.pi/2,0),bevel=0,segments=48)
v4.boolean(sleeve,inner_hole)

# ---- Spring-loaded applicator arm: pivot at shoulder, arm reaches down to roller -------
arm_profile=[(-0.014,0.145),(-0.010,0.151),(-0.005,0.151),(-0.064,0.080),(-0.093,0.044),(-0.103,0.031),(-0.095,0.065),(-0.030,0.143)]
side_plate('pressure_arm_web',arm_profile,-0.023,0.046,orange,arm,0.0018)
# Reinforcement rib on the arm, and hinge barrels/caps.
v4.rod('arm_stiffening_rib',(-0.021,-0.018,0.137),(-0.021,-0.085,0.058),0.003,material=orange_dark,body=arm)
for sx in (-1,1):
    x_cylinder('arm_hinge_barrel_'+str(sx),0.008,0.004,(sx*0.024,-0.006,0.142),steel,arm,0.0004)
# Visible torsion spring coil around hinge axis; two short tangs anchor on frame/arm.
for i in range(5):
    x_torus('hinge_spring_coil_%d'%i,0.010,0.0012,(-0.006+i*0.003,-0.006,0.142),steel,arm)
v4.rod('spring_tangent_arm',(-0.005,-0.013,0.134),(-0.016,-0.031,0.121),0.0014,material=steel,body=arm)
# pressure roller axle belongs to arm; wheel itself is separate spinning body.
x_cylinder('pressure_axle',0.0045,0.056,(0,-0.096,0.038),steel,arm,0.0003)

# Roller body: central dark rubber drum, pale end discs and thin steel rings.
x_cylinder('pressure_tread',0.014,0.050,(0,-0.096,0.038),roller_mat,press,0.001,64)
for sx in (-1,1):
    x_cylinder('pressure_endcap_'+str(sx),0.010,0.003,(sx*0.0265,-0.096,0.038),orange_dark,press,0.0005)
    x_cylinder('pressure_axle_button_'+str(sx),0.004,0.0015,(sx*0.0285,-0.096,0.038),steel,press,0.0004,32)
# Fine tread grooves around the roller circumference (subtle shallow rings).
for sx in (-1,1):
    x_torus('roller_shoulder_ring_'+str(sx),0.0125,0.00055,(sx*0.018,-0.096,0.038),black,press)

# ---- Serrated swinging cutter: hinged on the steel nose plate --------------------------
# Blade lies across tape width at rest. The triangular teeth project upward toward tape.
# Main cutting strip and repeated teeth are attached to the same moving blade body.
v4.box('blade_spine',(0.052,0.008,0.016),(0,-0.136,0.074),bevel=0.0007,material=steel,body=blade)
# Individual triangular teeth in side profile, across width, staggered as a real saw edge.
for i in range(21):
    x=-0.025+i*0.0025
    # Fine, sharply pointed teeth span the tape width at a practical pitch.
    side_plate('serration_%02d'%i,[(-0.143,0.080),(-0.136,0.089),(-0.129,0.080)],x-0.00095,0.0019,bright_steel,blade,0.00008)
# Blade hinge ears and axle are carried by the blade; fixed bracket contains matching supports.
for sx in (-1,1):
    x_cylinder('blade_hinge_ear_'+str(sx),0.0045,0.003,(sx*0.028,-0.132,0.064),steel,blade,0.0003)
# Fixed bracket cheeks straddle the hinge and show pins; already connected to frame via nose plate.
for sx in (-1,1):
    x_cylinder('fixed_blade_pivot_boss_'+str(sx),0.006,0.004,(sx*0.030,-0.132,0.064),orange_dark,frame,0.0005)
    x_cylinder('blade_pin_head_'+str(sx),0.0025,0.001,(sx*0.033,-0.132,0.064),steel,frame,0.0002,24)

# Joints: all real axes parallel to tape width (X).
v4.joint('roll_spin','continuous',frame,roll,origin=(0,0.045,0.116),axis=(1,0,0))
v4.joint('arm_hinge','revolute',frame,arm,origin=(0,-0.006,0.142),axis=(1,0,0),limits=(-0.22,0.22))
v4.joint('pressure_spin','continuous',arm,press,origin=(0,-0.096,0.038),axis=(1,0,0))
v4.joint('blade_hinge','revolute',frame,blade,origin=(0,-0.132,0.064),axis=(1,0,0),limits=(-0.12,0.32))

# Fuse each rigid assembly's touching mouldings into one watertight, connected mesh.
# Fine details remain at 1 mm voxel resolution, which also removes coincident internal faces.
for body_obj in (frame, roll, arm, press, blade):
    members=[]
    for ob in list(bpy.context.scene.objects):
        if ob.type not in {'MESH','CURVE','FONT'}:
            continue
        anc=ob
        while anc is not None and anc.get('v4_kind') != 'body':
            anc=anc.parent
        if anc is not None and anc.name == body_obj.name:
            members.append(ob)
    if not members: continue
    bpy.ops.object.select_all(action='DESELECT')
    for ob in members:
        ob.select_set(False)
        ob.parent=None
    if not members: continue
    bpy.ops.object.select_all(action='DESELECT')
    for ob in members:
        ob.select_set(True)
    bpy.context.view_layer.objects.active=members[0]
    bpy.ops.object.convert(target='MESH')
    # Cache source surfaces and material IDs so remeshing can retain the original finishes.
    source_surfaces=[]
    for src in members:
        if src.type != 'MESH' or not len(src.data.polygons):
            continue
        verts=[src.matrix_world @ v.co for v in src.data.vertices]
        faces=[tuple(p.vertices) for p in src.data.polygons]
        tree=BVHTree.FromPolygons(verts,faces)
        poly_mats=[src.data.materials[p.material_index] if src.data.materials else None for p in src.data.polygons]
        source_surfaces.append((tree,poly_mats))
    joined=bpy.context.view_layer.objects.active
    bpy.ops.object.join()
    joined.data.remesh_voxel_size=0.001
    joined.data.remesh_mode='VOXEL'
    bpy.ops.object.voxel_remesh()
    # Restore nearest-source surface material per remeshed face.
    mats=[]
    for _,pm in source_surfaces:
        for m in pm:
            if m is not None and m not in mats: mats.append(m)
    joined.data.materials.clear()
    for m in mats: joined.data.materials.append(m)
    for poly in joined.data.polygons:
        point=joined.matrix_world @ poly.center
        best=None; best_d=1e9; best_m=None
        for tree,pm in source_surfaces:
            hit=tree.find_nearest(point)
            if hit[0] is not None and hit[3] < best_d:
                best_d=hit[3]; best_m=pm[hit[2]]
        if best_m is not None: poly.material_index=mats.index(best_m)
        poly.use_smooth=True
    joined.name='fused_'+body_obj['v4_name']
    v4.part(joined,body_obj)

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