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

v4.reset()
# Materials: polished toy-shop maple, dark hardwood accents, enamel, brass and steel.
maple = v4.wood('honey_maple', light=(0.77,0.57,0.34), dark=(0.43,0.25,0.12), grain_scale=5.5)
walnut = v4.wood('walnut', light=(0.40,0.23,0.12), dark=(0.20,0.095,0.045), grain_scale=7)
endgrain = v4.wood('maple_endgrain', light=(0.65,0.43,0.24), dark=(0.34,0.18,0.08), grain_scale=10)
green = v4.painted('deep_green_enamel', (0.07,0.22,0.17), roughness=.27, coat=.7)
red = v4.painted('oxblood_enamel', (0.48,0.09,0.055), roughness=.25, coat=.65)
brass = v4.metal('satin_brass', color=(0.78,0.52,0.22), roughness=.27)
steel = v4.metal('turned_steel', color=(0.63,0.68,0.72), roughness=.28)
rubber = v4.rubber('foot_rubber', color=(.045,.04,.035))
marble_mat = v4.glass('cobalt_marble', color=(.13,.52,.9), roughness=.08)
black = v4.mat('letter_ink', (.055,.035,.02), roughness=.65)

# Dimensions: 460 mm wide, 300 mm deep, 580 mm high.
frame = v4.body('frame')
# Broad laminated plinth; front and side edging makes the board read as real timber.
v4.box('plinth_core', (.46,.30,.038), (0,0,.041), bevel=.006, material=walnut, body=frame)
v4.box('plinth_top', (.454,.294,.012), (0,0,.066), bevel=.004, material=maple, body=frame)
v4.box('front_inlay', (.36,.0025,.003), (0,-.149,.052), bevel=.001, material=brass, body=frame)
# Four turned feet and pads, touching the underside.
for ix,x in enumerate((-.184,.184)):
    for iy,y in enumerate((-.105,.105)):
        v4.lathe(f'foot_{ix}_{iy}', [(0,0),(.017,0),(.019,.006),(.016,.013),(.013,.018),(0,.018)],
                 loc=(x,y,.004), material=walnut, body=frame)
        v4.cylinder(f'foot_pad_{ix}_{iy}', .014,.004,(x,y,.002), bevel=.001, material=rubber, body=frame)
# Rear display board and top cap.
v4.box('rear_backboard', (.36,.022,.49), (0,.124,.315), bevel=.006, material=maple, body=frame)
v4.box('backboard_cap', (.38,.036,.018), (0,.124,.566), bevel=.006, material=walnut, body=frame)
# Decorative end-grain side uprights frame the lifting wheel.
for side,x in enumerate((-.184,.184)):
    v4.box(f'frame_upright_{side}', (.018,.038,.43),(x,.075,.287),bevel=.004,material=walnut,body=frame)
# Lift-column bearing cheeks and the top outlet nose, fitted around the wheel axle.
v4.box('axle_bearing_block', (.046,.022,.050),(.075,.045,.270),bevel=.006,material=green,body=frame)
v4.box('bearing_stand_off',(.046,.068,.018),(.075,.090,.270),bevel=.003,material=walnut,body=frame)
v4.cylinder('bearing_boss',.018,.004,(.075,.032,.270),rot=(math.pi/2,0,0),bevel=.001,material=brass,body=frame)
# Return course: three sloped runs, each is a pair of round wooden rails with steel ferrules.
# Rail centerline points; marbles travel from the elevated left end back to the lower elevator cup.
path=[(.075,.400),(-.176,.397),(-.036,.337),(.115,.258),(.115,.147)]
for side in (-1,1):
    yy=-.025+side*.023
    for k in range(len(path)-1):
        x0,z0=path[k]; x1,z1=path[k+1]
        # overlap adjacent rails by 2 mm to form a continuous track assembly
        dx=x1-x0; dz=z1-z0; ll=math.hypot(dx,dz); ux,uz=dx/ll,dz/ll
        ex0,ez0=(x0-ux*.006,z0-uz*.006) if k else (x0,z0)
        ex1,ez1=(x1+ux*.006,z1+uz*.006)
        v4.rod(f'return_rail_{side}_{k}',(ex0,yy,ez0),(ex1,yy,ez1),.0045,material=walnut,body=frame)
    # bed strip between the two rails, supported by the same return-course structure
    dx=x1-x0; dz=z1-z0; length=math.hypot(dx,dz); angle=math.atan2(dz,dx)
    v4.box(f'trough_bed_{k}',(length+.002,.052,.009),((x0+x1)/2,-.025,(z0+z1)/2-.007),rot=(0,-angle,0),bevel=.002,material=maple,body=frame)
# Slim trestles descend from the rails to the plinth, so the return course is structurally supported.
for i,(x,z) in enumerate(((-.15,.387),)):
    for side,y in enumerate((-.074,.024)):
        v4.rod(f'track_trestle_{i}_{side}',(x,y,.071),(x,y,z-.004),.0045,material=walnut,body=frame)
    v4.rod(f'trestle_crossbar_{i}',(x,-.076,z-.006),(x,.026,z-.006),.0045,material=brass,body=frame)

# Small cross ties below the open rail, visibly supporting the track.
for i,(x,z) in enumerate(((-.11,.37),(-.035,.337),(.045,.294),(.115,.20))):
    v4.rod(f'track_cross_tie_{i}',(x,-.047,z-.009),(x,-.003,z-.009),.004, square=True, bevel=.001,material=maple,body=frame)
# Catch pocket under wheel: floor, front lip and curved side cheeks.
v4.box('marble_sump_floor',(.105,.075,.012),(.112,-.022,.119),bevel=.004,material=green,body=frame)
for side in (-1,1):
    v4.box(f'sump_side_{side}',(.10,.008,.045),(.112,-.022+side*.036,.142),bevel=.003,material=maple,body=frame)
v4.box('sump_front_lip',(.105,.008,.028),(.112,-.064,.139),bevel=.003,material=walnut,body=frame)
# Gear guard mounting bosses and scale plate.
v4.box('maker_plate',(.112,.003,.030),(-.132,.110,.526),bevel=.002,material=brass,body=frame)
v4.box('plate_inset',(.102,.0015,.022),(-.132,.1077,.526),bevel=.001,material=green,body=frame)
v4.text('maker_mark','MARBLE WORKS',.009,(-.132,.1067,.528),rot=(math.pi/2,0,0),on=None)  # text is aligned below by explicit body
# Attach the standalone text object and keep it just proud of the inset plate.
textobj=v4.bpy.data.objects.get('maker_mark')
if textobj: v4.part(textobj,frame)
# Fine brass pinstripe on the fixed frame.


# Main hand crank and pinion gear, rotating about a transverse shaft.
crank=v4.body('crank')
cx,cz=-.060,.270
# pinion disc and teeth (gear face sits toward the viewer)
v4.cylinder('pinion_web',.043,.018,(cx,-.048,cz),rot=(math.pi/2,0,0),bevel=.002,material=green,body=crank)
v4.cylinder('pinion_hub',.015,.028,(cx,-.062,cz),rot=(math.pi/2,0,0),bevel=.002,material=brass,body=crank)
for i in range(12):
    a=2*math.pi*i/12
    x=cx+.046*math.cos(a); z=cz+.046*math.sin(a)
    v4.box(f'pinion_tooth_{i:02d}',(.010,.016,.012),(x,-.048,z),rot=(0,-a,0),bevel=.001,material=green,body=crank)
# Crank web runs from shaft to offset grip pin, in the visible wheel plane.
v4.rod('crank_web',(cx,-.047,cz),(cx-.060,-.047,cz),.006,material=brass,body=crank)
v4.cylinder('crank_root_collar',.010,.012,(cx,-.061,cz),rot=(math.pi/2,0,0),bevel=.001,material=steel,body=crank)
# A robust steel pin at the end of the crank web.
v4.cylinder('grip_pin',.005,.052,(cx-.060,-.075,cz),rot=(math.pi/2,0,0),bevel=.001,material=steel,body=crank)
v4.joint('crank_spin','continuous',frame,crank,origin=(cx,-.045,cz),axis=(0,1,0))
# Turned beech grip rotates independently on the crank pin.
grip=v4.body('crank_grip')
grx=cx-.060
gry=-.075
grz=cz
v4.lathe('turned_grip',[(0,-.025),(.008,-.025),(.011,-.019),(.012,-.010),(.011,.010),(.008,.020),(0,.020)],
         loc=(grx,gry,grz),rot=(math.pi/2,0,0),material=maple,body=grip)
for yy in (gry-.021,gry+.016):
    v4.cylinder('grip_end_cap_'+str(yy),.008,.003,(grx,yy,grz),rot=(math.pi/2,0,0),bevel=.0007,material=brass,body=grip)
v4.joint('grip_spin','continuous',crank,grip,origin=(grx,gry,grz),axis=(0,1,0))

# Large paddle wheel + matching gear, one rotating assembly on the lift column.
wheel=v4.body('paddle_wheel')
wx,wz=.075,.270
# Side rims and spokes are wood; open center keeps the lift mechanism readable.
v4.torus('wheel_rim_front',.108,.004,(wx,-.005,wz),rot=(math.pi/2,0,0),material=walnut,body=wheel)
v4.torus('wheel_rim_back',.108,.004,(wx,.006,wz),rot=(math.pi/2,0,0),material=walnut,body=wheel)
# Eight broad, slightly cupped lifting paddles spanning the wheel's front-to-back width.
for i in range(8):
    a=2*math.pi*i/8
    rad=.076
    x=wx+rad*math.cos(a); z=wz+rad*math.sin(a)
    v4.box(f'lift_paddle_{i:02d}',(.070,.038,.014),(x,-.018,z),rot=(0,-a,0),bevel=.004,material=maple,body=wheel)
    # short retaining end-stop at paddle tip, painted for visibility
    tx=wx+.106*math.cos(a); tz=wz+.106*math.sin(a)
    v4.box(f'paddle_lip_{i:02d}',(.014,.030,.022),(tx,-.018,tz),rot=(0,-a,0),bevel=.003,material=red,body=wheel)
# Hub barrel, decorative steel spokes, and accessible axle collars.
v4.cylinder('wheel_hub',.027,.060,(wx,-.018,wz),rot=(math.pi/2,0,0),bevel=.003,material=brass,body=wheel)
for i in range(8):
    a=2*math.pi*i/8
    v4.rod(f'wheel_spoke_{i}',(wx+.026*math.cos(a),-.018,wz+.026*math.sin(a)),
           (wx+.112*math.cos(a),-.018,wz+.112*math.sin(a)),.0035,material=green,body=wheel)
# Driven large gear on the forward face, with 20 teeth; it appears to mesh with the crank pinion.
v4.cylinder('bull_gear_web',.075,.014,(wx,-.056,wz),rot=(math.pi/2,0,0),bevel=.002,material=green,body=wheel)
v4.cylinder('bull_gear_hub',.019,.024,(wx,-.069,wz),rot=(math.pi/2,0,0),bevel=.002,material=brass,body=wheel)
for i in range(20):
    a=2*math.pi*i/20
    x=wx+.078*math.cos(a); z=wz+.078*math.sin(a)
    v4.box(f'bull_gear_tooth_{i:02d}',(.010,.014,.012),(x,-.056,z),rot=(0,-a,0),bevel=.001,material=green,body=wheel)
# Through axle and keeper collars.
v4.cylinder('wheel_axle',.006,.17,(wx,-.005,wz),rot=(math.pi/2,0,0),bevel=.0008,material=steel,body=wheel)
for side,y in enumerate((-.079,.069)):
    v4.cylinder(f'wheel_axle_keeper_{side}',.010,.004,(wx,y,wz),rot=(math.pi/2,0,0),bevel=.0008,material=brass,body=wheel)
v4.joint('wheel_spin','continuous',frame,wheel,origin=(wx,-.045,wz),axis=(0,1,0))

# Outlet track gate: transverse hinge pin and a polished paddle-shaped stop.
gate=v4.body('lever_gate')
gx,gy,gz=-.158,-.025,.392
v4.cylinder('gate_hinge_barrel',.005,.048,(gx,gy,gz),rot=(math.pi/2,0,0),bevel=.001,material=steel,body=gate)
v4.box('gate_blade',(.012,.040,.034),(gx+.006,gy,gz+.018),bevel=.003,material=red,body=gate)
v4.box('gate_top_cap',(.020,.046,.006),(gx+.006,gy,gz+.036),bevel=.003,material=brass,body=gate)
v4.joint('gate_hinge','revolute',frame,gate,origin=(gx,gy,gz),axis=(0,1,0),limits=(-.80,0.0))
# A blue glass marble in the lower catch makes the scale and intended use obvious.
v4.sphere('marble_in_catch',.013,(.112,-.023,.136),segments=32,material=marble_mat,body=frame)
# Brass trim rings on the exposed gear face and wheel.
v4.torus('pinion_face_ring',.030,.0013,(cx,-.058,cz),rot=(math.pi/2,0,0),material=brass,body=crank)
v4.torus('bull_face_ring',.052,.0013,(wx,-.064,wz),rot=(math.pi/2,0,0),material=brass,body=wheel)

# Scene setup and saved rest pose.
v4.rest()
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
