import math, os, sys
from mathutils import Vector
import bmesh
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()
# product materials
enamel = v4.painted('deep_forest_enamel', (0.075, 0.23, 0.16), roughness=0.24, coat=0.78)
trim = v4.painted('warm_ivory_enamel', (0.86, 0.78, 0.59), roughness=0.26, coat=0.72)
steel = v4.metal('satin_nickel', (0.72, 0.75, 0.76), roughness=0.28)
brass = v4.metal('aged_brass', (0.72, 0.48, 0.19), roughness=0.28)
black = v4.rubber('black_rubber', (0.035, 0.04, 0.038))
leather = v4.mat('dark_leather_pad', (0.12, 0.055, 0.028), roughness=0.68)
slotdark = v4.mat('slot_interior', (0.025, 0.028, 0.027), roughness=0.8)
red = v4.painted('indicator_red', (0.68, 0.11, 0.065), roughness=0.23, coat=0.7)

base = v4.body('base')
# Dimensions: 180 wide x 130 deep housing; lower shell and softly rounded shoulders.
# The main casting provides the continuous structural shell.
cast = v4.box('cast_lower_case', (0.18, 0.13, 0.085), (0, 0, 0.0535), bevel=0.012, material=enamel, body=base)
# Button well and lower collection-drawer tunnel are cut into the casting.
cutter = v4.cylinder('button_bore_cutter', 0.014, 0.034, (0,-0.051,0.052), rot=(math.pi/2,0,0), bevel=0)
v4.boolean(cast, cutter)
drawer_cutter=v4.box('drawer_cavity_cutter',(0.108,0.100,0.038),(0,-0.019,0.029),bevel=0)
v4.boolean(cast,drawer_cutter)
# Wider stepped base plinth gives the bank a substantial furniture-like stance.
v4.box('bottom_plinth',(0.190,0.140,0.010),(0,0,0.012),bevel=0.004,material=trim,body=base)
v4.box('plinth_shadow_line',(0.184,0.134,0.002),(0,0,0.018),bevel=0.001,material=brass,body=base)
# Raised cream trim band wrapping the front and sides at the shoulder seam.
v4.box('front_pinstripe', (0.153, 0.0022, 0.004), (0, -0.0652, 0.084), bevel=0.0015, material=trim, body=base)
for sx in (-1,1):
    v4.box('side_pinstripe_'+str(sx), (0.0022, 0.112, 0.004), (sx*0.0901, 0, 0.084), bevel=0.0015, material=trim, body=base)
    # Cast corner bead with polished edge, seated into the front casting.
    v4.rod('front_corner_bead_'+str(sx),(sx*0.085,-0.0655,0.022),(sx*0.085,-0.0655,0.086),0.0015,material=brass,body=base)
    v4.cylinder('corner_bead_cap_'+str(sx),0.002,0.0015,(sx*0.085,-0.066,0.086),rot=(math.pi/2,0,0),segments=24,material=steel,body=base)
# Top deck plate, with ivory perimeter lip.
v4.box('top_deck', (0.174, 0.124, 0.014), (0, 0, 0.102), bevel=0.006, material=trim, body=base)
v4.box('deck_inset', (0.164, 0.114, 0.004), (0, 0, 0.111), bevel=0.003, material=enamel, body=base)
# Coin tray: shallow recessed well bounded by rounded lips, open at the front.
v4.box('tray_floor', (0.108, 0.061, 0.004), (0, -0.015, 0.115), bevel=0.004, material=steel, body=base)
for sx in (-1,1):
    v4.box('tray_rail_'+str(sx), (0.004, 0.066, 0.012), (sx*0.056, -0.015, 0.123), bevel=0.0018, material=brass, body=base)
# Raised receiving hood at the paddle's release arc. Its front-facing slit is framed in brass.
v4.box('receiver_foot',(0.090,0.028,0.008),(0,0.010,0.116),bevel=0.002,material=brass,body=base)
receiver=v4.box('receiver_backplate',(0.080,0.007,0.048),(0,0.005,0.166),bevel=0.0025,material=enamel,body=base)
# Recessed dark coin slit and bright raised slot frame on the hood's front face.
v4.box('receiver_slot_shadow',(0.046,0.0012,0.003),(0,0.0012,0.172),bevel=0.0012,material=slotdark,body=base)
for z in (0.169,0.175):
    v4.box('receiver_slot_lip_'+str(z),(0.050,0.002,0.0014),(0,0.0004,z),bevel=0.0005,material=brass,body=base)
for sx in (-1,1):
    v4.box('receiver_slot_end_'+str(sx),(0.0015,0.002,0.007),(sx*0.025,0.0004,0.172),bevel=0.0005,material=brass,body=base)
# Side cheek plates and broad hood roof form a recognizable coin catcher.
for sx in (-1,1):
    v4.box('receiver_cheek_'+str(sx),(0.006,0.032,0.050),(sx*0.039,0.015,0.140),bevel=0.002,material=brass,body=base)
v4.box('receiver_hood',(0.090,0.036,0.006),(0,0.015,0.192),bevel=0.003,material=trim,body=base)
v4.box('receiver_hood_inset',(0.060,0.020,0.0015),(0,0.013,0.1953),bevel=0.001,material=enamel,body=base)
# Small screws on the hood's shoulders.
for sx in (-1,1):
    v4.cylinder('receiver_fastener_'+str(sx),0.0018,0.0015,(sx*0.031,0.0008,0.166),rot=(math.pi/2,0,0),segments=20,material=steel,body=base)
# Spring axle brackets at rear of the tray.
ax_y, ax_z = -0.039, 0.132
for sx in (-1,1):
    v4.box('pivot_pedestal_'+str(sx), (0.010, 0.018, 0.019), (sx*0.043, ax_y, 0.1285), bevel=0.002, material=enamel, body=base)
    v4.cylinder('pivot_bracket_boss_'+str(sx), 0.007, 0.006, (sx*0.049, ax_y, ax_z), rot=(0,math.pi/2,0), material=brass, body=base)
    v4.cylinder('pivot_screw_'+str(sx), 0.0027, 0.007, (sx*0.053, ax_y, ax_z), rot=(0,math.pi/2,0), segments=24, material=steel, body=base)
# Continuous multi-turn torsion spring, with both reaction tails reaching the fixed axle brackets.
# Building one swept mesh keeps the winding physically continuous and visibly wraps the X axle.
coil_r, wire_r = 0.0055, 0.00105
centerline=[]
for j in range(16):
    t=j/15
    centerline.append(Vector((-0.043+0.033*t,ax_y+coil_r,ax_z)))
for j in range(1,201):
    t=j/200
    a=math.tau*5*t
    centerline.append(Vector((-0.010+0.020*t,ax_y+coil_r*math.cos(a),ax_z+coil_r*math.sin(a))))
for j in range(1,16):
    t=j/15
    centerline.append(Vector((0.010+0.033*t,ax_y+coil_r,ax_z)))
coil_bm=bmesh.new(); coil_rings=[]; sides=12
for i,p in enumerate(centerline):
    tangent=(centerline[min(i+1,len(centerline)-1)]-centerline[max(i-1,0)]).normalized()
    theta=0.0 if i<16 else (math.tau*5*(i-15)/200 if i<=215 else math.tau*5)
    radial=Vector((0,math.cos(theta),math.sin(theta)))
    normal=(radial-tangent.dot(radial)*tangent).normalized()
    binormal=tangent.cross(normal).normalized()
    ring=[]
    for k in range(sides):
        a=math.tau*k/sides
        ring.append(coil_bm.verts.new(p+wire_r*(math.cos(a)*normal+math.sin(a)*binormal)))
    coil_rings.append(ring)
for i in range(len(coil_rings)-1):
    for k in range(sides):
        coil_bm.faces.new((coil_rings[i][k],coil_rings[i][(k+1)%sides],coil_rings[i+1][(k+1)%sides],coil_rings[i+1][k]))
for ring, p, reverse in ((coil_rings[0],centerline[0],True),(coil_rings[-1],centerline[-1],False)):
    cap=coil_bm.verts.new(p)
    for k in range(sides):
        face=(ring[(k+1)%sides],ring[k],cap) if reverse else (ring[k],ring[(k+1)%sides],cap)
        coil_bm.faces.new(face)
bmesh.ops.recalc_face_normals(coil_bm,faces=coil_bm.faces)
coil_obj=v4._mesh_obj('torsion_spring_coil',coil_bm)
v4._finish(coil_obj,base,steel,0.0,smooth=True)
# Front plunger guide, raised metal escutcheon and markings.
esc=v4.cylinder('button_escutcheon', 0.018, 0.003, (0,-0.0664,0.052), rot=(math.pi/2,0,0), material=brass, body=base)
esc_cut=v4.cylinder('escutcheon_bore',0.014,0.010,(0,-0.066,0.052),rot=(math.pi/2,0,0),bevel=0)
v4.boolean(esc,esc_cut)
# Operation plate on front right.
v4.box('instruction_plate', (0.044,0.0018,0.022), (0.058,-0.0656,0.054), bevel=0.002, material=brass, body=base)
v4.text('plate_press', 'PUSH', 0.0052, loc=(0.058,-0.06665,0.058), rot=(math.pi/2,0,0), extrude_depth=0.00025, material=slotdark, body=base)
v4.text('plate_flip', 'PLUNGER', 0.0034, loc=(0.058,-0.06665,0.051), rot=(math.pi/2,0,0), extrude_depth=0.00025, material=slotdark, body=base)
# front brand plaque
v4.box('brand_badge', (0.077,0.0018,0.010), (0,-0.0658,0.030), bevel=0.002, material=trim, body=base)
v4.text('brand_text', 'BANK', 0.008, loc=(0,-0.0669,0.028), rot=(math.pi/2,0,0), extrude_depth=0.0002, material=enamel, body=base)
# Feet: four short rubber pads with nickel rims.
for sx in (-1,1):
    for sy in (-1,1):
        x,y=sx*0.076,sy*0.054
        v4.cylinder('foot_rim_'+str(sx)+str(sy), 0.011, 0.004, (x,y,0.010), material=steel, body=base)
        v4.cylinder('rubber_foot_'+str(sx)+str(sy), 0.009, 0.010, (x,y,0.005), material=black, body=base)
# Collection slot behind the lower front panel. Drawer runs on shallow fixed rails.
dz=0.028
for sx in (-1,1):
    v4.box('drawer_runner_'+str(sx), (0.006,0.073,0.006), (sx*0.047,-0.005,0.014), bevel=0.001, material=steel, body=base)
# front drawer slot frame surrounds a close-fitting aperture
v4.box('drawer_slot_lip', (0.112,0.003,0.038), (0,-0.0655,0.029), bevel=0.004, material=trim, body=base)
v4.box('drawer_slot_shadow', (0.092,0.001,0.022), (0,-0.0673,0.029), bevel=0.002, material=slotdark, body=base)
# Visible release lever bracket on upper right deck.
lever_p=(0.075,-0.020,0.1285)
v4.box('lever_mount', (0.022,0.026,0.009), (0.075,-0.020,0.118), bevel=0.003, material=enamel, body=base)
for sx in (-1,1):
    v4.box('lever_ear_'+str(sx), (0.004,0.014,0.014), (0.075+sx*0.008,-0.020,0.1285), bevel=0.0015, material=brass, body=base)
# engraved small maker info on right deck
v4.box('release_label_plate',(0.014,0.038,0.0015),(0.075,-0.044,0.114),bevel=0.001,material=brass,body=base)
v4.text('deck_label','RELEASE',0.0052,loc=(0.075,-0.044,0.1149),rot=(0,0,math.pi/2),extrude_depth=0.0002,material=slotdark,body=base)

# Trip button assembly: cap, ribbed crown, stem and a raised actuator pin behind the face.
button=v4.body('trip_button')
v4.cylinder('plunger_stem',0.006,0.016,(0,-0.0655,0.052),rot=(math.pi/2,0,0),material=steel,body=button)
# Lathed red cap has a short shoulder and a convex dome, so it reads as a push plunger.
v4.lathe('domed_push_cap',[(0,0),(0.008,0),(0.0115,0.0015),(0.0115,0.003),(0.0108,0.005),(0.0085,0.007),(0.005,0.0087),(0,0.0095)],loc=(0,-0.0695,0.052),rot=(math.pi/2,0,0),material=red,body=button)
v4.cylinder('plunger_center_badge',0.0028,0.0008,(0,-0.0788,0.052),rot=(math.pi/2,0,0),segments=32,material=trim,body=button)
v4.joint('button_slide','prismatic',base,button,origin=(0,-0.064,0.052),axis=(0,1,0),limits=(0,0.010))

# Trip lever swings horizontally and its latch tip engages the flip-arm spine.
lever=v4.body('trip_lever')
v4.cylinder('lever_hub', 0.005, 0.012, lever_p, material=steel, body=lever)
# 68 mm pawl bar reaches across from the handle pivot to the flip-arm catch.
v4.rod('pawl_link', (0.074,-0.020,0.1285), (0.007,-0.020,0.1285), 0.0026, material=brass, body=lever)
# A separate 44 mm release handle swings visibly beside its marked label.
v4.rod('release_handle',(0.075,-0.020,0.1285),(0.075,-0.062,0.1285),0.0032,material=brass,body=lever)
v4.sphere('release_knob',0.006,(0.075,-0.0635,0.1285),material=black,body=lever)
v4.torus('release_knob_bead',0.0055,0.0007,(0.075,-0.0635,0.1285),rot=(math.pi/2,0,0),material=brass,body=lever)
v4.sphere('lever_latch_tip',0.0026,(0.007,-0.020,0.1285),material=steel,body=lever)
v4.cylinder('lever_pivot_pin', 0.0025, 0.016, lever_p, material=brass, body=lever)
v4.joint('trip_lever_hinge','revolute',base,lever,origin=lever_p,axis=(0,0,1),limits=(-math.radians(14),0))

# Spring-loaded flip arm. At rest paddle lies just above the front half of tray;
# rotation about X drives it up and rearward toward the receiver.
arm=v4.body('flip_arm')
# pivot axle and central arm root
v4.cylinder('arm_axle',0.0035,0.092,(0,ax_y,ax_z),rot=(0,math.pi/2,0),material=steel,body=arm)
# paddle spine runs along +Y from pivot; wide contact paddle at its distal end
v4.rod('flip_arm_spine',(0,ax_y,ax_z),(0,0.007,0.125),0.0032,material=brass,body=arm)
# Steel latch lug is mounted on the spine exactly where the pawl rests against it.
v4.box('flip_arm_latch_lug',(0.004,0.007,0.006),(0.002,-0.020,0.129),bevel=0.0012,material=steel,body=arm)
paddle=v4.box('flip_paddle',(0.055,0.017,0.006),(0,0.003,0.123),bevel=0.003,material=brass,body=arm)
# Shallow coin seat machined into the paddle face, with a dark leather insert at its floor.
coin_cut=v4.cylinder('paddle_coin_cut',0.0085,0.0015,(0,0.003,0.1255),bevel=0)
v4.boolean(paddle,coin_cut)
v4.cylinder('paddle_coin_seat',0.007,0.0006,(0,0.003,0.12505),segments=48,material=leather,body=arm)
v4.box('paddle_leather_face',(0.047,0.0015,0.003),(0,0.003,0.1195),bevel=0.0015,material=leather,body=arm)
# crosswise ribbed grip / stiffener near paddle end
v4.cylinder('paddle_rivet_l',0.0018,0.002,( -0.023,0.003,0.1265),rot=(0,math.pi/2,0),segments=20,material=steel,body=arm)
v4.cylinder('paddle_rivet_r',0.0018,0.002,( 0.023,0.003,0.1265),rot=(0,math.pi/2,0),segments=20,material=steel,body=arm)
v4.joint('flip_arm_hinge','revolute',base,arm,origin=(0,ax_y,ax_z),axis=(1,0,0),limits=(0,math.radians(72)))

# Pull-out coin drawer, three-sided nickel tray and dark felt floor.
drawer=v4.body('coin_drawer')
front_y=-0.066
v4.box('drawer_face',(0.104,0.016,0.029),(0,front_y,dz),bevel=0.003,material=enamel,body=drawer)
v4.box('drawer_face_inlay',(0.063,0.0012,0.010),(0,front_y-0.0046,dz),bevel=0.0015,material=brass,body=drawer)
v4.text('drawer_mark','CHANGE',0.0048,loc=(0,front_y-0.00535,dz-0.0015),rot=(math.pi/2,0,0),extrude_depth=0.0002,material=slotdark,body=drawer)
# tray inside the lip, dimensions 90 x 65 x 20 mm
# One manifold tray shell: floor, three walls, and rolled top rim share vertices.
import bmesh
bm=bmesh.new()
outer=[(-0.048,-0.059,0.016),(0.048,-0.059,0.016),(0.048,0.009,0.016),(-0.048,0.009,0.016)]
outer_top=[(x,y,0.037) for x,y,_ in outer]
inner_top=[(-0.045,-0.056,0.037),(0.045,-0.056,0.037),(0.045,0.006,0.037),(-0.045,0.006,0.037)]
inner_bot=[(x,y,0.019) for x,y,_ in inner_top]
rings=[[bm.verts.new(p) for p in ring] for ring in (outer,outer_top,inner_top,inner_bot)]
for i in range(4):
    j=(i+1)%4
    bm.faces.new((rings[0][i],rings[0][j],rings[1][j],rings[1][i]))
    bm.faces.new((rings[1][i],rings[1][j],rings[2][j],rings[2][i]))
    bm.faces.new((rings[2][i],rings[2][j],rings[3][j],rings[3][i]))
bm.faces.new(tuple(rings[0]))
bm.faces.new(tuple(reversed(rings[3])))
bmesh.ops.recalc_face_normals(bm,faces=bm.faces)
tray=v4._mesh_obj('drawer_tray_shell',bm)
v4._finish(tray,drawer,steel,0.0008)
# shallow pull bead on face
v4.rod('drawer_pull',( -0.013,front_y-0.009,dz),(0.013,front_y-0.009,dz),0.0022,material=brass,body=drawer)
v4.joint('drawer_slide','prismatic',base,drawer,origin=(0,-0.025,dz),axis=(0,-1,0),limits=(0,0.060))

# Tiny retaining coin is fixed in a vertical display position behind the slot, out of arm sweep.
# Omit a loose tray coin so the paddle remains unobstructed during its full rotation.
# Side seam screws and a small red travel indicator add mass-produced detail.
for sx in (-1,1):
    for z in (0.037,0.071):
        v4.cylinder(f'case_screw_{sx}_{z}',0.002,0.0018,(sx*0.0904,-0.023,z),rot=(0,math.pi/2,0),segments=20,material=steel,body=base)

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