"""Curved, spring-hinged tortoiseshell claw clip."""
import math
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import bmesh
from mathutils import Vector
import v4lib as v4

v4.reset()

# Warm translucent tortoiseshell: broad amber/brown mottling under a clear coat.
tortoise = v4.plastic("amber_tortoiseshell", (0.30, 0.12, 0.045), roughness=0.21, texture=0.03)
nt = tortoise.node_tree
bsdf = nt.nodes.get("Principled BSDF")
noise = nt.nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = 58.0
noise.inputs["Detail"].default_value = 3.0
noise.inputs["Roughness"].default_value = 0.72
noise.inputs["Distortion"].default_value = 3.5
coord = nt.nodes.new("ShaderNodeTexCoord")
nt.links.new(coord.outputs["Object"], noise.inputs["Vector"])
ramp = nt.nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].position = 0.25
ramp.color_ramp.elements[0].color = (0.018, 0.004, 0.001, 1)
ramp.color_ramp.elements[1].position = 0.70
ramp.color_ramp.elements[1].color = (0.24, 0.085, 0.018, 1)
e = ramp.color_ramp.elements.new(0.48)
e.color = (0.085, 0.022, 0.004, 1)
nt.links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
nt.links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
bsdf.inputs["Coat Weight"].default_value = 0.42
bsdf.inputs["Coat Roughness"].default_value = 0.18
bsdf.inputs["Transmission Weight"].default_value = 0.12
# The channel interior is the same molded acetate with a softer, less reflective finish.
inner_tortoise = v4.plastic("satin_inner_tortoiseshell", (0.30, 0.12, 0.045), roughness=0.34, texture=0.03)
ibsdf = inner_tortoise.node_tree.nodes.get("Principled BSDF")
ibsdf.inputs["Coat Weight"].default_value = 0.16
ibsdf.inputs["Coat Roughness"].default_value = 0.30
ibsdf.inputs["Transmission Weight"].default_value = 0.06
ins = inner_tortoise.node_tree.nodes.new("ShaderNodeTexNoise")
ins.inputs["Scale"].default_value = 58.0
ins.inputs["Detail"].default_value = 3.0
ins.inputs["Roughness"].default_value = 0.72
ins.inputs["Distortion"].default_value = 3.5
ic = inner_tortoise.node_tree.nodes.new("ShaderNodeTexCoord")
inner_tortoise.node_tree.links.new(ic.outputs["Object"], ins.inputs["Vector"])
ir = inner_tortoise.node_tree.nodes.new("ShaderNodeValToRGB")
ir.color_ramp.elements[0].position = 0.25
ir.color_ramp.elements[0].color = (0.018, 0.004, 0.001, 1)
ir.color_ramp.elements[1].position = 0.70
ir.color_ramp.elements[1].color = (0.24, 0.085, 0.018, 1)
ie = ir.color_ramp.elements.new(0.48)
ie.color = (0.085, 0.022, 0.004, 1)
inner_tortoise.node_tree.links.new(ins.outputs["Fac"], ir.inputs["Fac"])
inner_tortoise.node_tree.links.new(ir.outputs["Color"], ibsdf.inputs["Base Color"])
metal = v4.metal("polished_spring_steel", (0.78, 0.80, 0.82), roughness=0.22, brushed=False)
padmat = v4.rubber("dark_brown_grip", (0.09, 0.045, 0.025), roughness=0.72)
markmat = v4.mat("warm_engraving", (0.90, 0.59, 0.30), metallic=0.2, roughness=0.3)

lower = v4.body("lower_jaw")
upper = v4.body("upper_jaw")

# Overall envelope about 108 x 44 x 57 mm; jaw itself is 84 x 40 mm (2.1:1).
# Hinge runs along Y; the two long jaws sweep away from the pivot along +X.
hx, hz = -0.040, 0.025

# Curved shell loft. Each section is a thin, broad lenticular molded jaw, with
# the tab, hinge neck, arched jaw and tapered tip built as one continuous surface.
def catmull(points, t):
    n = len(points) - 1
    u = max(0.0, min(0.999999, t)) * n
    i = int(u)
    f = u - i
    p0 = points[max(0, i-1)]
    p1 = points[i]
    p2 = points[i+1]
    p3 = points[min(n, i+2)]
    return tuple(0.5*((2*p1[k]) + (-p0[k]+p2[k])*f + (2*p0[k]-5*p1[k]+4*p2[k]-p3[k])*f*f + (-p0[k]+3*p1[k]-3*p2[k]+p3[k])*f*f*f) for k in range(len(p1)))

def jaw_shell(name, body, keys, width_keys, thick_keys):
    # A closed, shallow U channel across the width: recessed center, curled raised rims.
    # The inner and outer skins share a rounded profile and are separately finished.
    nlong = 65
    profile = [-1.0, -0.91, -0.76, -0.50, 0.0, 0.50, 0.76, 0.91, 1.0]
    nring = len(profile) * 2
    sign = 1 if body == lower else -1
    verts, faces = [], []
    for i in range(nlong):
        t = i/(nlong-1)
        x,z = catmull(keys, t)
        # tangent and its perpendicular in the XZ side-view plane
        ta = catmull(keys, min(0.9999, t+0.001))
        tb = catmull(keys, max(0.0, t-0.001))
        dx, dz = ta[0]-tb[0], ta[1]-tb[1]
        ll = math.hypot(dx,dz) or 1.0
        nx, nz = -dz/ll, dx/ll
        halfw = catmull(width_keys, t)[0]
        halfth = catmull(thick_keys, t)[0]
        # Outer edges curl toward the opposing comb; the center is a shallow trough.
        for j, s in enumerate(profile):
            y = halfw * s
            lip = 0.0042 * (abs(s) ** 4)
            trough = -0.0012 * (1.0 - abs(s))
            surface = lip + trough
            # Inner skin, facing the matching jaw.
            verts.append((x + nx * (sign * surface), y, z + nz * (sign * surface)))
        for j in reversed(range(len(profile))):
            s = profile[j]
            y = halfw * s
            lip = 0.0042 * (abs(s) ** 4)
            trough = -0.0012 * (1.0 - abs(s))
            surface = lip + trough - halfth
            verts.append((x + nx * (sign * surface), y, z + nz * (sign * surface)))
    for i in range(nlong-1):
        for j in range(nring):
            a = i*nring+j
            b = i*nring+(j+1)%nring
            faces.append((a,b,b+nring,a+nring))
    faces.append(tuple(range(nring-1,-1,-1)))
    faces.append(tuple((nlong-1)*nring+j for j in range(nring)))
    mesh = bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    v4.assign(obj, tortoise)
    obj.data.materials.append(inner_tortoise)
    # Profile edges on the first half are the visible channel skin.
    for poly in mesh.polygons:
        if poly.index < (nlong - 1) * len(profile):
            poly.material_index = 1
    for p in mesh.polygons:
        p.use_smooth = True
    edge = obj.modifiers.new("Molded shell edge radius", "BEVEL")
    edge.width = 0.00028
    edge.segments = 2
    edge.limit_method = "ANGLE"
    edge.angle_limit = 0.65
    v4.part(obj, body)
    return obj

# keypoints trace rear squeeze tab -> hinge -> curved C jaw -> closing nose.
# The lower jaw curves down 18 mm; its mate curves upward 18 mm.
lower_keys = [(-0.067,0.004),(-0.054,0.008),(-0.040,0.025),(-0.019,0.014),(0.002,0.007),(0.025,0.012),(0.044,0.025)]
upper_keys = [(-0.067,0.046),(-0.054,0.042),(-0.040,0.025),(-0.019,0.036),(0.002,0.043),(0.025,0.038),(0.044,0.025)]
# Cross-jaw half-width and shell half-thickness along the complete loft. Tabs flare gently.
width_keys = [(0.016,), (0.012,), (0.006,), (0.012,), (0.020,), (0.016,), (0.009,)]
thick_keys = [(0.0040,), (0.0045,), (0.0012,), (0.0026,), (0.0022,), (0.0015,), (0.00065,)]
jaw_shell("lower_curved_shell", lower, lower_keys, width_keys, thick_keys)
upper_thick_keys = list(thick_keys)
upper_thick_keys[2] = (0.0002,)  # spring clearance at the hinge; knuckles carry the load here
jaw_shell("upper_curved_shell", upper, upper_keys, width_keys, upper_thick_keys)

# Dense, tapered comb teeth. The half-pitch shift and opposed lean let the two combs
# enter the spaces between one another when closed. Each tine has a gentle sweep.
def curved_tine(name, body, x, y, z, dirx, dirz, tanx, tanz):
    nseg, nring = 7, 10
    length = 0.016
    verts, faces = [], []
    radii = [0.00165,0.00158,0.00148,0.00132,0.00112,0.00091,0.00069,0.00048]
    for i in range(nseg+1):
        u = i/nseg
        cx = x + dirx*length*u + tanx*0.0025*u*u
        cz = z + dirz*length*u + tanz*0.0025*u*u
        vx=dirx*length+tanx*0.005*u; vz=dirz*length+tanz*0.005*u
        ll=math.hypot(vx,vz) or 1.0
        nx,nz=-vz/ll,vx/ll
        r = radii[i]
        for j in range(nring):
            a=2*math.pi*j/nring
            # Broad, flattened oval sections give the prongs a molded comb profile.
            verts.append((cx+r*1.04*nx*math.cos(a),y+r*1.22*math.sin(a),cz+r*1.04*nz*math.cos(a)))
    for i in range(nseg):
        for j in range(nring):
            a=i*nring+j; b=i*nring+(j+1)%nring
            faces.append((a,b,b+nring,a+nring))
    faces.append(tuple(range(nring-1,-1,-1)))
    faces.append(tuple(nseg*nring+j for j in range(nring)))
    mesh=bpy.data.meshes.new(name+"_mesh"); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); bpy.context.scene.collection.objects.link(obj)
    v4.assign(obj,tortoise)
    for poly in mesh.polygons: poly.use_smooth=True
    v4.part(obj,body)

def interp(keys, t): return catmull(keys, t)
tooth_count=10
for i in range(tooth_count):
    tl=0.47+i*0.033
    tu=tl+0.0165
    for tag,body,keys,thickness,t,sign in (("lower",lower,lower_keys,thick_keys,tl,1),
                                           ("upper",upper,upper_keys,upper_thick_keys,tu,-1)):
        x,z=interp(keys,t)
        halfw=interp(width_keys,t)[0]
        before=interp(keys,max(0,t-0.001)); after=interp(keys,min(0.9999,t+0.001))
        tx,tz=after[0]-before[0],after[1]-before[1]
        ll=math.hypot(tx,tz) or 1.0; tx,tz=tx/ll,tz/ll
        nx,nz=-tz,tx
        # Two rows grow from the curled lips; the upper comb is half a pitch ahead.
        lip=0.0042*(0.82**4)-0.0012*(1.0-0.82)
        rootx=x+sign*nx*lip
        rootz=z+sign*nz*lip
        for edge in (-1,1):
            y=edge*halfw*0.82
            curved_tine(f"{tag}_tine_{i}_{'L' if edge < 0 else 'R'}",body,
                        rootx,y,rootz,0.0,float(sign),1.0,0.0)

# Concave, rounded grip inserts sit flush on the outward face of each flared handle.
def z_on_handle(keys,x):
    for i in range(len(keys)-1):
        a,b=keys[i],keys[i+1]
        if a[0] <= x <= b[0]:
            f=(x-a[0])/(b[0]-a[0])
            return a[1]*(1-f)+b[1]*f
    return keys[0][1] if x<keys[0][0] else keys[-1][1]

def grip_patch(name, body, keys, sign):
    # Concentric oval rings make a true rounded outline and a dish across the pad.
    nring,nrad=32,7
    verts=[(-0.0575,0,z_on_handle(keys,-0.0575)+sign*0.00315)]
    faces=[]
    for ri in range(1,nrad+1):
        r=ri/nrad
        for j in range(nring):
            a=2*math.pi*j/nring
            x=-0.0575+0.0080*r*math.cos(a)
            y=0.0065*r*math.sin(a)
            zc=z_on_handle(keys,x)
            # Pad lip sits on the thickened outer shell, with a shallow central dish.
            z=zc+sign*(0.0057+0.00045*r*r)
            verts.append((x,y,z))
    for j in range(nring):
        faces.append((0,1+j,1+(j+1)%nring) if sign>0 else (0,1+(j+1)%nring,1+j))
    for ri in range(nrad-1):
        first=1+ri*nring; nxt=first+nring
        for j in range(nring):
            a=first+j; b=first+(j+1)%nring
            c=nxt+(j+1)%nring; d=nxt+j
            faces.append((a,b,c,d) if sign>0 else (a,d,c,b))
    mesh=bpy.data.meshes.new(name+"_mesh"); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); bpy.context.scene.collection.objects.link(obj)
    v4.assign(obj,padmat)
    for poly in mesh.polygons: poly.use_smooth=True
    solid=obj.modifiers.new("Grip pad thickness","SOLIDIFY"); solid.thickness=0.00055; solid.offset=0.0
    bevel=obj.modifiers.new("Soft grip edge","BEVEL"); bevel.width=0.00035; bevel.segments=3
    v4.part(obj,body)

grip_patch("lower_concave_grip",lower,lower_keys,-1)
grip_patch("upper_concave_grip",upper,upper_keys,1)
v4.text("maker_mark", "MIRA", 0.0028, loc=(-0.061,-0.003,0.0515),
        extrude_depth=0.00022, material=markmat, body=upper)

# Split alternating hinge knuckles leave a central channel for the torsion coil.
# The coil sits between the paired upper knuckles, inside the overall barrel assembly.
for sy in (-1,1):
    v4.cylinder(f"lower_hinge_knuckle_{sy}", 0.0043, 0.008, (hx,sy*0.014, hz),
                rot=(math.pi/2,0,0), segments=32, bevel=0.0004, material=tortoise, body=lower)
    v4.cylinder(f"upper_hinge_knuckle_{sy}", 0.0043, 0.004, (hx,sy*0.006, hz),
                rot=(math.pi/2,0,0), segments=32, bevel=0.0004, material=tortoise, body=upper)
v4.cylinder("retained_pivot_pin", 0.0018, 0.040, (hx,0,hz), rot=(math.pi/2,0,0),
            segments=32, bevel=0.0002, material=metal, body=lower)

# Dome-ended caps match the 8.6 mm barrel diameter and sit close to its outer ends.
cap_profile=[(0,0),(0.0034,0),(0.0040,0.00035),(0.0043,0.0008),(0.0043,0.0013),
             (0.0040,0.0020),(0.0032,0.0028),(0.0020,0.0035),(0.0008,0.0040),(0,0.0042)]
v4.lathe("pivot_cap_positive",cap_profile,loc=(hx,0.0195,hz),rot=(-math.pi/2,0,0),
         material=metal,body=lower)
v4.lathe("pivot_cap_negative",cap_profile,loc=(hx,-0.0195,hz),rot=(math.pi/2,0,0),
         material=metal,body=lower)

# Compact helical torsion coil in the central hinge gap. Its two formed legs press
# against the inner faces of the squeeze handles at the closed rest pose.
coil=[]
for i in range(161):
    t=i/160
    a=2*math.pi*2.5*t
    y=-0.004 + 0.008*t
    coil.append((hx + 0.0032*math.cos(a), y, hz + 0.0032*math.sin(a)))
v4.tube("visible_torsion_coil", coil, 0.00065, material=metal, body=upper, resolution=10)
# Coil end coordinates: the lower leg remains with the lower jaw; the upper leg
# bears on the moving handle and therefore follows the upper jaw.
v4.tube("spring_lower_leg",[(hx+0.0032,-0.004,hz),(-0.047,-0.004,0.013),(-0.054,-0.004,0.007)],
        0.00065,material=metal,body=lower,resolution=8)
v4.tube("spring_upper_leg",[(hx-0.0032,0.004,hz),(-0.047,0.004,0.037),(-0.054,0.004,0.043)],
        0.00065,material=metal,body=upper,resolution=8)
# Formed spring legs bear on the two jaw bodies near the hinge.

# Upper jaw opens away from the lower shell at its free end. The negative Y rotation
# raises the +X nose and pushes the rear squeeze tab down.
v4.joint("jaw_hinge", "revolute", lower, upper, origin=(hx,0,hz), axis=(0,1,0),
         limits=(-math.radians(55),0))

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