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

v4.reset()
# Finishes
white = v4.painted("warm_white_powdercoat", (0.88, 0.86, 0.80), roughness=0.31, coat=0.35)
rail_white = v4.painted("rail_satin_white", (0.91, 0.89, 0.83), roughness=0.28, coat=0.45)
alum = v4.metal("anodized_aluminum", (0.68, 0.70, 0.72), roughness=0.3, brushed=True)
steel = v4.metal("zinc_plated_steel", (0.70, 0.72, 0.73), roughness=0.28, brushed=False)
nylon = v4.plastic("charcoal_nylon", (0.095, 0.105, 0.11), roughness=0.43)
cream = v4.fabric("woven_ivory_ladder_tape", (0.77, 0.72, 0.61), weave_scale=220)
cordmat = v4.fabric("braided_lift_cord", (0.83, 0.79, 0.69), weave_scale=300)
clear = v4.mat("clear_acrylic", (0.75, 0.83, 0.85), roughness=0.18, coat=0.7)
ink = v4.mat("badge_ink", (0.15, 0.18, 0.19), roughness=0.5)

W=1.20; ZTOP=1.60; rail_z=1.552; yfront=-0.012
root=v4.body("headrail")
# U-channel: formed top, back and front lips, with end plates
v4.box("headrail_top", (W, .058, .004), (0, 0, ZTOP-.002), bevel=.0015, material=white, body=root)
v4.box("headrail_back_wall", (W, .004, .048), (0, .027, ZTOP-.028), bevel=.0012, material=white, body=root)
v4.box("headrail_front_lip", (W, .004, .030), (0, -.027, ZTOP-.038), bevel=.001, material=rail_white, body=root)
for s in (-1,1):
    x=s*(W/2-.002)
    v4.box("headrail_endcap_%s"%s, (.004,.058,.048), (x,0,ZTOP-.028), bevel=.0015, material=nylon, body=root)
    # real wall-mount bracket folded plate, two ears, screw heads
    bx=s*.48
    v4.box("bracket_top_%s"%s, (.095,.075,.003), (bx,.006,ZTOP+.002), bevel=.001, material=steel, body=root)
    v4.box("bracket_back_%s"%s, (.095,.003,.050), (bx,.039,ZTOP-.025), bevel=.001, material=steel, body=root)
    for dx in (-.031,.031):
        v4.cylinder("bracket_screw_%s_%s"%(s,dx), .004, .002, (bx+dx,.036,ZTOP-.025), rot=(math.pi/2,0,0), material=steel, body=root)
# fascia/faceplate and small badge
v4.box("front_fascia", (W-.018,.003,.012), (0,-.030,ZTOP-.010), bevel=.002, material=rail_white, body=root)
v4.box("maker_badge", (.075,.001,.008), (.40,-.032,ZTOP-.010), bevel=.001, material=steel, body=root)
v4.text("badge_mark", "NOVA 25", .005, (.40,-.033,ZTOP-.010), rot=(math.pi/2,0,0), extrude_depth=.0002, material=ink, body=root)
# Gearbox and cord-lock housings, mounted beneath end portions
v4.box("tilt_gear_housing", (.090,.050,.041), (-.535,-.005,1.538), bevel=.007, material=nylon, body=root)
v4.box("gearbox_cover_seam", (.071,.002,.025), (-.535,-.031,1.538), bevel=.003, material=white, body=root)
v4.cylinder("gearbox_boss", .006,.012,(-.535,-.039,1.538),rot=(math.pi/2,0,0),material=steel,body=root)
v4.box("cord_lock_shell", (.105,.045,.043), (.505,-.003,1.538), bevel=.006, material=nylon, body=root)
v4.box("cord_lock_release", (.030,.012,.010), (.505,-.032,1.520), bevel=.003, material=white, body=root)
# tilt shaft axial inside headrail; details are on shaft body
shaft=v4.body("tilt_shaft")
v4.rod("hex_tilt_rod",(-.62,.005,1.568),(.44,.005,1.568),.0045,segments=6,bevel=0,material=steel,body=shaft)
for x in (-.40,.40):
    v4.cylinder("tape_spool_%s"%x,.012,.018,(x,.005,1.568),rot=(0,math.pi/2,0),material=nylon,body=shaft)
v4.cylinder("worm_gear",.012,.014,(-.602,-.005,1.568),rot=(0,math.pi/2,0),material=steel,body=shaft)
v4.joint("tilt_shaft_mount","continuous",root,shaft,origin=(0,.005,1.568),axis=(1,0,0))
# Wand body, swivel hook and clear acrylic stem
wand=v4.body("wand")
v4.torus("wand_swivel_eye",.013,.003,loc=(-.535,-.041,1.542),rot=(math.pi/2,0,0),material=steel,body=wand)
v4.rod("wand_stem",(-.535,-.048,1.525),(-.535,-.075,.27),.0055,material=clear,body=wand)
v4.lathe("wand_grip",[(0,0),(.008,0),(.009,.012),(.008,.105),(.007,.12),(0,.12)],loc=(-.535,-.075,.15),material=nylon,body=wand)
v4.joint("wand_swivel","continuous",root,wand,origin=(-.535,-.041,1.542),axis=(0,0,1))
# Slats: continuous stamped aluminum profiles, one articulated body per blade
N=16; z0=.135; pitch=.085; L=1.16; depth=.050; thick=.00075
slats=[]
for i in range(N):
    z=z0+i*pitch
    b=v4.body("slat_%02d"%(i+1)); slats.append(b)
    # shallow crowned blade as a segmented sheet with turned down rolled edges; cross-section along YZ
    xs=[-L/2,L/2]
    yz=[(-depth/2,0),(-depth*.34,.0010),(0,.0015),(depth*.34,.0010),(depth/2,0),
        (depth/2,-.0014),(depth*.34,-.0002),(0,.0003),(-depth*.34,-.0002),(-depth/2,-.0014)]
    verts=[]
    for x in xs:
        for y,dz in yz: verts.append((x,y,z+dz))
    faces=[]; m=len(yz)
    faces.append(tuple(range(m-1,-1,-1))); faces.append(tuple(range(m,2*m)))
    for j in range(m): faces.append((j,(j+1)%m,(j+1)%m+m,j+m))
    mesh=__import__('bpy').data.meshes.new("slat_profile_%02d"%(i+1)); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=__import__('bpy').data.objects.new("curved_aluminum_slat_%02d"%(i+1),mesh)
    __import__('bpy').context.scene.collection.objects.link(obj); v4._finish(obj,b,alum,.00025)
    # tiny cord eyelet grommets at cord lines, nestled on blade
    for x in (-.34,.34):
        v4.torus("cord_eyelet_%02d_%s"%(i+1,x),.0042,.00065,loc=(x,-.001,z+.0011),rot=(0,0,0),material=steel,body=b)
    # plastic hem end caps seated on the blade ends
    for s in (-1,1):
        v4.box("slat_endcap_%02d_%s"%(i+1,s),(.012,.023,.003), (s*(L/2-.006),0,z-.0002),bevel=.001,material=white,body=b)
    # Woven ladder cross-rungs sit under the slat at each of the two tape stations.
    # They are carried by the blade so they follow its tilt instead of remaining
    # as unrelated static threads in front of it.
    for x in (-.42,.42):
        v4.rod("ladder_rung_%02d_%s"%(i+1,x),(x,-.0275,z-.002),(x,.0275,z-.002),.0013,material=cream,body=b)
    sj=v4.joint("slat_mount_%02d"%(i+1),"revolute",root,b,origin=(0,0,z),axis=(1,0,0),limits=(-math.radians(80),math.radians(80)))
    sj["v4_mimic_joint"]="tilt_shaft_mount"; sj["v4_mimic_ratio"]=1.0
# Four ladder strands form two front/rear tapes, with cross-rungs carried by each slat.
tape_lines=[]
for side,x in (("left",-.42),("right",.42)):
    for face,y in (("front",-.0275),("rear",.0275)):
        tape_lines.append(v4.rod("ladder_tape_%s_%s"%(side,face),(x,y,1.585),(x,y,.091),.0013,material=cream,body=root))
# Lift cords through cord lock with visible top routing, down through eyelets and ending on bottom rail
# Two cords share a body with rail so they travel with the rail; fixed upper segments remain rooted.
rail=v4.body("lift_rail")
railz=.08
v4.box("bottom_rail_extrusion",(1.18,.030,.022),(0,0,railz),bevel=.004,material=rail_white,body=rail)
for s in (-1,1):
    x=s*.59
    v4.box("bottom_endcap_%s"%s,(.018,.034,.023),(x,0,railz),bevel=.004,material=nylon,body=rail)
    # visible short cord tail anchor entering rail
    v4.tube("lift_cord_tail_%s"%s,[(s*.34,-.001,railz+.011),(s*.34,-.001,railz+.030)],.0024,material=cordmat,body=rail)
# Cord path is stationary except endpoints are hidden in the rail. Main vertical drops finish just above the rail.
lift_lines=[]
for s,x in (("L",-.34),("R",.34)):
    lift_lines.append(v4.rod("lift_line_%s"%s,(x,-.001,1.602),(x,-.001,.091),.0018,material=cordmat,body=root))
v4.joint("lift_slide","prismatic",root,rail,origin=(0,0,railz),axis=(0,0,1),limits=(0,1.40))
# Distinct pull cord exits the cord lock at the end opposite the tilt wand.
pull=v4.body("pull_cord")
external_lift_cord=v4.rod("external_lift_cord",(.515,-.040,1.516),(.515,-.040,.900),.0028,material=cordmat,body=pull)
tassel=v4.lathe("lift_cord_tassel",[(0,0),(.006,0),(.009,.008),(.010,.020),(.008,.050),(.006,.062),(0,.066)],loc=(.515,-.040,.834),material=nylon,body=pull)
v4.joint("cord_pull","prismatic",root,pull,origin=(.515,-.040,1.516),axis=(0,0,-1),limits=(0,1.40))

# Mimic relationships: twisting the wand rotates the tilt shaft and all blades.
# Pulling the bottom rail upward picks each blade up after contact and gathers it
# into a compact, level stack directly above the rail.
import bpy
wand_joint=bpy.data.objects["J_wand_swivel"]
pull_body=bpy.data.objects["B_pull_cord"]
lift_joint=bpy.data.objects["J_lift_slide"]
lift_body=bpy.data.objects["B_lift_rail"]
cord_joint=bpy.data.objects["J_cord_pull"]
shaft_joint=bpy.data.objects["J_tilt_shaft_mount"]
shaft_joint["v4_mimic_joint"]="wand_swivel"; shaft_joint["v4_mimic_ratio"]=-1.0

def channel_driver(obj, channel, expression, variables):
    fcurve=obj.driver_add(channel[0],channel[1])
    drv=fcurve.driver; drv.type="SCRIPTED"; drv.expression=expression
    for spec in variables:
        var_name, target_obj, path = spec[:3]
        space = spec[3] if len(spec) > 3 else "LOCAL_SPACE"
        v=drv.variables.new(); v.name=var_name; v.type="TRANSFORMS"
        t=v.targets[0]; t.id=target_obj; t.transform_type=path; t.transform_space=space

# J_tilt_drive's local Euler Y is negative for positive rotation about world X.
channel_driver(shaft_joint,("rotation_euler",1),"-a",[("a",wand_joint,"ROT_Z","WORLD_SPACE")])
for line in lift_lines:
    # Keep each lift line taut between the headrail and the rising bottom rail.
    channel_driver(line,("scale",2),"max(0.001,(1.602-(b+0.011))/1.511)",[("b",lift_body,"LOC_Z","WORLD_SPACE")])
    channel_driver(line,("location",2),"(1.602+b+0.011)/2",[("b",lift_body,"LOC_Z","WORLD_SPACE")])
for tape in tape_lines:
    # Keep tape ends on the moving rail while the free span retracts into the headrail.
    channel_driver(tape,("scale",2),"max(0.001,(1.598-(b+0.011))/1.507)",[("b",lift_body,"LOC_Z","WORLD_SPACE")])
    channel_driver(tape,("location",2),"(1.598+b+0.011)/2",[("b",lift_body,"LOC_Z","WORLD_SPACE")])
# The pull cord slides downward through a fixed top guide; scale its visible span
# while the cord body translates so its top remains in the cord lock.
channel_driver(external_lift_cord,("scale",2),"1+(1.516-c)/0.616",[("c",cord_joint,"LOC_Z","WORLD_SPACE")])
channel_driver(external_lift_cord,("location",2),"1.208-0.5*(1.516-c)-b",[("b",pull_body,"LOC_Z","WORLD_SPACE"),("c",cord_joint,"LOC_Z","WORLD_SPACE")])
channel_driver(tassel,("location",2),"0.834-(1.516-c)-b",[("b",pull_body,"LOC_Z","WORLD_SPACE"),("c",cord_joint,"LOC_Z","WORLD_SPACE")])
for i in range(N):
    name="J_slat_mount_%02d"%(i+1)
    j=bpy.data.objects[name]
    z=z0+i*pitch
    target_z=1.390+i*.005
    # lift_joint local Z is the rail centre height (0.08 m at rest).
    channel_driver(j,("location",2),f"{z:.6f}+min({target_z-z:.6f},max(0,b-({z-.011:.6f})))",
                   [("b",lift_joint,"LOC_Z","WORLD_SPACE")])
    channel_driver(j,("rotation_euler",1),"0 if b>0.09 else min(1.3962634,max(-1.3962634,a))",
                   [("a",shaft_joint,"ROT_Y","LOCAL_SPACE"),("b",lift_joint,"LOC_Z","WORLD_SPACE")])

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