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

v4.reset()
# Materials: marine hardware, anodized parts, weather-sealed motor, and cover.
steel = v4.metal('304 stainless steel', (0.72, 0.76, 0.78), roughness=0.25)
brushed = v4.metal('brushed aluminum', (0.67, 0.72, 0.75), roughness=0.3)
blue = v4.painted('anodized deep blue', (0.055, 0.22, 0.34), roughness=0.24, coat=0.65)
framecoat = v4.painted('graphite powder coat', (0.12, 0.15, 0.17), roughness=0.31, coat=0.5)
black = v4.rubber('EPDM rubber', (0.025, 0.03, 0.032))
poly = v4.plastic('bearing polymer', (0.08, 0.10, 0.11), roughness=0.48)
motor_mat = v4.painted('motor charcoal enamel', (0.075, 0.09, 0.095), roughness=0.28, coat=0.45)
vinyl = v4.painted('opaque blue pool-cover vinyl', (0.045, 0.24, 0.48), roughness=0.31, coat=0.28)
seam = v4.fabric('cover edge reinforcement', (0.018, 0.17, 0.21), weave_scale=300)
white = v4.mat('ivory marking', (0.88, 0.9, 0.83), roughness=0.5)
green = v4.emissive('green status LED', (0.08, 0.82, 0.27), strength=1.7)

frame = v4.body('frame')
drum = v4.body('drum')
# Scale and layout
AXZ=0.66
XEND=2.48
# helpers
def cyl_x(name, x, y, z, r, depth, mat, body, bevel=0.001):
    return v4.cylinder(name, r, depth, (x,y,z), rot=(0, math.pi/2, 0), segments=48, bevel=bevel, material=mat, body=body)
def tor_x(name, x,y,z,major,minor,mat,body):
    return v4.torus(name, major, minor, (x,y,z), rot=(0,math.pi/2,0), segments=80, ring_segments=16, material=mat, body=body)

# ----- fixed tripod end supports: wide cross feet and upright bearing masts -----
for s, side in [(-1,'L'),(1,'R')]:
    x=s*XEND
    # T-foot and upright meet on their flat faces; the foot itself rests on the ground.
    v4.rod(f'{side}_cross_foot',(x,-0.43,0.044),(x,0.43,0.044),0.024,square=True,material=framecoat,body=frame)
    v4.rod(f'{side}_upright',(x,0,0.068),(x,0,0.618),0.021,square=True,material=framecoat,body=frame)
    # Paired diagonal braces turn each mast and foot into a rigid triangular end frame.
    for sy, tag in [(-1,'front'),(1,'rear')]:
        v4.rod(f'{side}_{tag}_support_brace',(x,sy*0.385,0.070),(x,sy*0.025,0.375),0.017,square=True,material=steel,body=frame)
    # Single annular pillow bushing: its bore is concentric with the axle and the mast meets its underside.
    tor_x(f'{side}_pillow_bushing',x,0,AXZ,0.036,0.010,blue,frame)
    for sy,tag in [(-1,'front'),(1,'rear')]:
        v4.rod(f'{side}_{tag}_bearing_gusset',(x,sy*0.014,0.49),(x,sy*0.045,0.625),0.012,material=blue,body=frame)
        v4.extrude(f'{side}_{tag}_bearing_gusset_plate',[(0,0),(0.20,0),(0.10,0.14)],0.012,
                   loc=(x-0.10,sy*0.034,0.48),rot=(sy*math.pi/2,0,0),bevel=0.003,material=blue,body=frame)

# Longitudinal low stabilizer tying the two end feet into one portable frame.
v4.rod('rear_base_stabilizer',(-XEND,0.40,0.044),(XEND,0.40,0.044),0.019,square=True,material=steel,body=frame)
v4.rod('front_base_stabilizer',(-XEND,-0.40,0.044),(XEND,-0.40,0.044),0.019,square=True,material=steel,body=frame)
# Rubber leveling pads at the four rectangular base corners.
for sx in (-1,1):
    for sy in (-1,1):
        v4.cylinder(f'corner_leveling_pad_{sx}_{sy}',0.047,0.020,(sx*XEND,sy*0.40,0.011),bevel=0.004,material=black,body=frame)
        v4.cylinder(f'corner_pad_washer_{sx}_{sy}',0.022,0.003,(sx*XEND,sy*0.40,0.022),bevel=0.001,material=steel,body=frame)
        v4.box(f'floor_anchor_plate_{sx}_{sy}',(0.13,0.14,0.014),(sx*XEND,sy*0.40,0.028),bevel=0.004,material=blue,body=frame)
        for dx in (-0.045,0.045):
            v4.cylinder(f'anchor_plate_bolt_{sx}_{sy}_{dx}',0.006,0.004,(sx*XEND+dx,sy*0.40,0.037),bevel=0.001,material=steel,body=frame)

# Fixed poolside feed tongue sits 6 mm below the bottom of the wound cover roll.
# A U-shaped guide cradle supports the short flat vinyl strip while the roll turns independently.
FEED_Z=0.567
v4.box('stationary_pool_cover_feed',(4.10,0.48,0.004),(0,-0.24,FEED_Z),bevel=0.002,material=vinyl,body=frame)
v4.rod('feed_outer_crossbar',(-XEND,-0.48,FEED_Z),(XEND,-0.48,FEED_Z),0.012,square=True,material=blue,body=frame)
for sx,tag in [(-1,'left'),(1,'right')]:
    v4.rod(f'feed_side_rail_{tag}',(sx*XEND,0,FEED_Z),(sx*XEND,-0.48,FEED_Z),0.012,square=True,material=blue,body=frame)

# Motor and reduction gearbox fixed to right stand, output aligned to drum axle.
# Fixed casing sits outboard of the right bearing. Layered motor barrel, end bell, ribs and gland.
v4.rod('gearbox_support_arm',(2.48,0,AXZ-0.046),(2.67,0,AXZ-0.046),0.016,square=True,material=framecoat,body=frame)
# A pair of formed torque arms support the outboard motor shell on the right upright.
for sy,tag in [(-1,'near'),(1,'far')]:
    v4.rod(f'motor_torque_arm_{tag}',(2.47,sy*0.025,AXZ-0.12),(2.78,sy*0.025,AXZ-0.12),0.018,square=True,material=blue,body=frame)
# Four slim stanchions and a rounded lid form a guard over the exposed shaft coupling.
for xx in (2.53,2.64):
    for sy,tag in [(-1,'near'),(1,'far')]:
        v4.rod(f'coupling_guard_stanchion_{xx}_{tag}',(xx,sy*0.040,AXZ-0.102),(xx,sy*0.040,AXZ+0.058),0.006,square=True,material=blue,body=frame)
v4.box('coupling_protective_shroud',(0.18,0.12,0.012),(2.585,0,AXZ+0.064),bevel=0.012,material=blue,body=frame)
v4.text('coupling_safety_mark','DRIVE',0.035,(2.585,-0.062,AXZ+0.066),rot=(math.pi/2,0,0),extrude_depth=0.0004,material=white,body=frame)
v4.cylinder('sealed_reducer_body',0.112,0.20,(2.76,0,AXZ),rot=(0,math.pi/2,0),bevel=0.012,material=motor_mat,body=frame)
v4.cylinder('reducer_outboard_endbell',0.126,0.035,(2.875,0,AXZ),rot=(0,math.pi/2,0),bevel=0.008,material=blue,body=frame)
v4.cylinder('motor_stator_can',0.095,0.30,(3.035,0,AXZ),rot=(0,math.pi/2,0),bevel=0.009,material=motor_mat,body=frame)
v4.cylinder('motor_rear_cap',0.105,0.035,(3.203,0,AXZ),rot=(0,math.pi/2,0),bevel=0.007,material=framecoat,body=frame)
# axial cooling ribs along motor can, with axial end rings
for i in range(12):
    a=2*math.pi*i/12
    y,z=0.093*math.cos(a), AXZ+0.093*math.sin(a)
    v4.rod(f'motor_cooling_fin_{i}',(2.94,y,z),(3.13,y,z),0.006,material=steel,body=frame)
for x in (2.93,3.13): tor_x(f'motor_rib_ring_{x}',x,0,AXZ,0.096,0.004,steel,frame)
# Top cover hood and visible controller lid keep the weatherproof assembly enclosed.
v4.box('motor_top_shroud',(0.38,0.22,0.014),(3.00,0,AXZ+0.103),bevel=0.012,material=blue,body=frame)
for sx in (-1,1):
    for sy in (-1,1):
        v4.cylinder(f'motor_shroud_screw_{sx}_{sy}',0.006,0.004,(3.00+sx*0.15,sy*0.075,AXZ+0.112),bevel=0.001,material=steel,body=frame)
# outboard control box face looks toward the camera (-Y)
v4.box('motor_control_box',(0.20,0.14,0.20),(2.79,-0.132,AXZ+0.015),bevel=0.022,material=motor_mat,body=frame)
v4.box('control_faceplate',(0.145,0.009,0.145),(2.79,-0.207,AXZ+0.015),bevel=0.012,material=blue,body=frame)
v4.box('controller_weather_lid',(0.18,0.12,0.012),(2.79,-0.132,AXZ+0.122),bevel=0.009,material=blue,body=frame)
for dx in (-0.07,0.07):
    for dy in (-0.04,0.04):
        v4.cylinder(f'controller_lid_screw_{dx}_{dy}',0.005,0.003,(2.79+dx,-0.132+dy,AXZ+0.13),bevel=0.001,material=steel,body=frame)
v4.text('maker_badge','AQUA  /  DRIVE',0.023,(2.79,-0.213,AXZ+0.046),rot=(math.pi/2,0,0),extrude_depth=0.0005,material=white,body=frame)
v4.cylinder('sealed_green_indicator',0.012,0.009,(2.79,-0.215,AXZ-0.005),rot=(math.pi/2,0,0),bevel=0.003,material=green,body=frame)
# two sealed push buttons below status lamp
for xx, col in [(2.75,red if False else steel),(2.83,steel)]:
    v4.cylinder(f'control_button_{xx}',0.012,0.008,(xx,-0.215,AXZ-0.052),rot=(math.pi/2,0,0),bevel=0.002,material=col,body=frame)
# cable gland and cable loop anchored to motor top/rear
v4.cylinder('cable_gland',0.018,0.035,(3.10,0,AXZ+0.105),bevel=0.004,material=steel,body=frame)
v4.tube('motor_power_cable',[(3.10,0,AXZ+0.12),(3.12,0.10,AXZ+0.14),(3.05,0.18,AXZ+0.14),(2.93,0.18,AXZ+0.14)],0.007,material=black,body=frame)
# motor fasteners at face and reducer
for yy in (-0.075,0.075):
    for zz in (AXZ-0.075,AXZ+0.075):
        cyl_x(f'motor_cap_screw_{yy}_{zz}',3.224,yy,zz,0.008,0.006,steel,frame,0.001)

# ----- rotating telescoping drum and drive shaft -----
# Four nested tube spans with slight step changes that telescope in a real reel.
sections=[(-2.34,-1.30,0.080,brushed),(-1.30,-0.20,0.077,steel),(-0.20,1.05,0.077,brushed),(1.05,2.34,0.080,steel)]
for i,(a,b,r,m) in enumerate(sections):
    cyl_x(f'telescoping_drum_tube_{i+1}',(a+b)/2,0,AXZ,r,b-a,m,drum,0.0015)
    # colored indexing bands near overlap joints
    if i>0:
        tor_x(f'tube_overlap_bead_{i}',a+0.025,0,AXZ,r+0.0015,0.003,blue,drum)
# axle stubs pass through pillow bearings; captured collars just inside and outside supports
cyl_x('left_axle_stub',-2.47,0,AXZ,0.026,0.42,steel,drum,0.002)
cyl_x('right_drive_axle',2.46,0,AXZ,0.030,0.40,steel,drum,0.002)
for x, s in [(-2.31,-1),(2.31,1)]:
    tor_x(f'inner_shaft_retainer_{s}',x,0,AXZ,0.031,0.005,blue,drum)
# End collars with radial side flanges; circular flanges bound the rolled fabric.
for x,side in [(-2.18,'left'),(2.18,'right')]:
    cyl_x(f'{side}_drum_end_collar',x,0,AXZ,0.091,0.09,blue,drum,0.004)
    cyl_x(f'{side}_cover_retaining_disc',x+(-0.075 if side=='left' else 0.075),0,AXZ,0.165,0.018,brushed,drum,0.004)
    tor_x(f'{side}_flange_bead',x+(-0.086 if side=='left' else 0.086),0,AXZ,0.143,0.004,blue,drum)
    # six small flange fasteners around each face
    face_x=x+(-0.086 if side=='left' else 0.086)
    for k in range(6):
        a=2*math.pi*k/6
        cyl_x(f'{side}_flange_bolt_{k}',face_x,0.145*math.cos(a),AXZ+0.145*math.sin(a),0.007,0.006,steel,drum,0.001)
# Three strap clamps around drum, with low-profile bridge cleats and threaded fasteners.
for i,x in enumerate((-1.38,0,1.38)):
    tor_x(f'cover_strap_band_{i+1}',x,0,AXZ,0.080,0.0045,blue,drum)
    v4.box(f'strap_bridge_{i+1}',(0.095,0.040,0.009),(x,-0.001,AXZ+0.085),bevel=0.003,material=steel,body=drum)
    v4.box(f'strap_webbing_tab_{i+1}',(0.062,0.019,0.006),(x,-0.002,AXZ+0.093),bevel=0.002,material=seam,body=drum)
    for dx in (-0.033,0.033):
        v4.cylinder(f'strap_screw_{i+1}_{dx}',0.005,0.006,(x+dx,-0.001,AXZ+0.091),bevel=0.001,material=steel,body=drum)

# A thin cover sheet winds around the telescoping core; it stays entirely on the drum,
# with no rotating flap. Five and a half turns build about 5 mm of layered cover.
def make_cover():
    bm=bmesh.new()
    xs=(-2.12,-2.075,-1.40,-1.36,-0.02,0.02,1.36,1.40,2.075,2.12)
    path=[]
    start=-math.pi/2
    wraps=5.5
    steps=440
    for j in range(steps+1):
        ang=start+2*math.pi*wraps*j/steps
        rr=0.078 + 0.001*(wraps*j/steps)
        path.append((rr*math.cos(ang), AXZ+rr*math.sin(ang)))
    n=len(path)
    verts=[]
    for x in xs:
        for y,z in path: verts.append(bm.verts.new((x,y,z)))
    faces=[]
    for ix in range(len(xs)-1):
        for j in range(n-1):
            face=bm.faces.new((verts[ix*n+j],verts[ix*n+j+1],verts[(ix+1)*n+j+1],verts[(ix+1)*n+j]))
            # Reinforced hems and subtle wrap index marks make the roll legible in motion.
            if ix in (0,len(xs)-2,2,4,6) or (j < steps and j % 80 in (0,1)):
                face.material_index=1
            faces.append(face)
    bmesh.ops.recalc_face_normals(bm,faces=faces)
    me=bpy.data.meshes.new('teal_cover_mesh')
    bm.to_mesh(me)
    obj=bpy.data.objects.new('teal_cover_roll',me)
    bm.free()
    v4._finish(obj,drum,vinyl,0.0,smooth=False)
    obj.data.materials.clear()
    obj.data.materials.append(vinyl)
    obj.data.materials.append(seam)
    return obj
make_cover()
# 250 mm four-spoke hand winding wheel on the left axle end.
cyl_x('left_handwheel_hub',-2.70,0,AXZ,0.032,0.040,blue,drum,0.003)
tor_x('left_handwheel_rim',-2.70,0,AXZ,0.112,0.009,black,drum)
for k in range(4):
    a=math.pi*k/2
    y0,z0=0.025*math.cos(a),AXZ+0.025*math.sin(a)
    y1,z1=0.108*math.cos(a),AXZ+0.108*math.sin(a)
    v4.rod(f'left_handwheel_spoke_{k}',(-2.70,y0,z0),(-2.70,y1,z1),0.008,material=brushed,body=drum)
v4.cylinder('handwheel_grip',0.016,0.080,(-2.70,0,AXZ-0.108),rot=(0,math.pi/2,0),bevel=0.006,material=black,body=drum)

v4.joint('drum_axle','continuous',frame,drum,origin=(0,0,AXZ),axis=(1,0,0))
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
