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

v4.reset()

def txt(name, string, size, loc=(0,0,0), rot=(0,0,0), material=None, body=None):
    # Fine molded/printed legends sit nearly flush so they read as markings rather than raised blocks.
    return v4.text(name, string, size, loc=loc, rot=rot, extrude_depth=0.00008, material=material, body=body)

# Finishes
shell = v4.plastic('graphite_polycarbonate', (0.045,0.055,0.066), roughness=0.29, texture=0.12)
shell2 = v4.plastic('rear_soft_touch', (0.075,0.083,0.09), roughness=0.48, texture=0.2)
black = v4.rubber('black_elastomer', (0.012,0.015,0.018))
metal = v4.metal('satin_stainless', (0.58,0.64,0.69), roughness=0.24)
chrome = v4.metal('polished_trackball_bezel', (0.78,0.82,0.84), roughness=0.16, brushed=False)
keymat = v4.plastic('keycap_charcoal', (0.22,0.24,0.25), roughness=0.27, texture=0.08)
keylight = v4.plastic('keycap_pearl', (0.72,0.75,0.76), roughness=0.25, texture=0.06)
legend = v4.mat('legend_ice', (0.72,0.86,0.9), roughness=0.4)
legend_dim = v4.mat('legend_secondary', (0.40,0.50,0.53), roughness=0.5)
call_ink = v4.mat('call_icon_green', (0.08,0.42,0.18), roughness=0.32)
end_ink = v4.mat('end_icon_red', (0.58,0.10,0.08), roughness=0.32)
port_metal = v4.metal('bottom_port_bezel', (0.34,0.39,0.43), roughness=0.24)
bezel = v4.mat('display_black_bezel', (0.008,0.012,0.018), metallic=0.12, roughness=0.2, coat=0.5)
glass = v4.mat('display_glass', (0.006,0.018,0.032), metallic=0.06, roughness=0.23, coat=0.2)
ui_blue = v4.emissive('display_blue_ui', (0.10,0.48,0.8), 0.8)
ui_white = v4.emissive('display_white_ui', (0.65,0.83,0.96), 0.65)
led = v4.emissive('green_status_led', (0.08,0.85,0.28), 1.5)
covermat = v4.plastic('battery_cover_polymer', (0.095,0.105,0.112), roughness=0.38, texture=0.16)

# Coordinates: handset is 116 x 63 x 12 mm, face upward (+Z), display end at +Y.
W, L = 0.063, 0.116
SIM_Y, SIM_Z = .039, .0068
KEY_SHIFT_Y = .0040
KEY_X_SCALE = 1.0
KEY_STROKE = .0005
BATTERY_SHIFT_Y = .0035
BATTERY_COVER_Y = -.024 + BATTERY_SHIFT_Y
BATTERY_COVER_Z = .0019
chassis = v4.body('chassis')
# Main shell and brushed perimeter rails. The chassis back plane starts at z=1.4 mm.
main_shell = v4.box('main_unibody_shell', (W, L, .0108), (0,0,.0068), bevel=.0025, material=shell, body=chassis)
# Hairline chrome side rails, interrupted only at the SIM access slot.
for sx in (-1,1):
    x=sx*(W/2-.00025)
    if sx < 0:
        lo=-.051
        hi=SIM_Y-.0079
        v4.box('side_band_lower_'+str(sx),(.00055,hi-lo,.0007),(x,(lo+hi)/2,.0069),bevel=.00022,material=metal,body=chassis)
        lo=SIM_Y+.0079
        hi=.051
        v4.box('side_band_upper_'+str(sx),(.00055,hi-lo,.0007),(x,(lo+hi)/2,.0069),bevel=.00022,material=metal,body=chassis)
    else:
        v4.box('side_band_'+str(sx), (.00055,.102,.0007), (x,0,.0069), bevel=.00022, material=metal, body=chassis)
    # side volume rocker two tactile buttons on right flank
    if sx > 0:
        for j, yy in enumerate((.018,.010)):
            v4.box('side_volume_'+str(j), (.0015,.006,.0020), (sx*(W/2+.0003),yy,.0083), bevel=.0008, material=keylight, body=chassis)
        v4.box('side_mute_slider', (.0013,.008,.0016), (sx*(W/2+.00025),-.002,.0082), bevel=.0005, material=black, body=chassis)
    else:
        v4.box('power_key', (.0015,.008,.0020), (sx*(W/2+.0003),.027,.0083), bevel=.0008, material=keylight, body=chassis)
# antenna seam interruption lines
for sx in (-1,1):
    for yy in (-.040,.041):
        v4.box('antenna_break',(.0010,.0014,.0031),(sx*(W/2-.0004), yy,.0069),bevel=.0002,material=black,body=chassis)
# Front bezel surround as top panel and bottom chin, with central display glass
v4.box('display_black_bezel', (.052,.048,.0008), (0,.032,.0116), bevel=.0010, material=bezel, body=chassis)
v4.box('display_frame_left',(.0005,.0415,.00010),(-.0240,.032,.01220),bevel=.00015,material=chrome,body=chassis)
v4.box('display_frame_right',(.0005,.0415,.00010),(.0240,.032,.01220),bevel=.00015,material=chrome,body=chassis)
v4.box('display_frame_top',(.0475,.0005,.00010),(0,.0530,.01220),bevel=.00015,material=chrome,body=chassis)
v4.box('display_frame_bottom',(.0475,.0005,.00010),(0,.0110,.01220),bevel=.00015,material=chrome,body=chassis)
v4.box('display_lens', (.0475,.0415,.00035), (0,.032,.01215), bevel=.0012, material=glass, body=chassis)
# Screen interface inside screen; restrained status bar, clock, icon tiles, text
v4.box('screen_status_bar',(.045,.004,.00012),(0,.0502,.01236),bevel=.0004,material=ui_blue,body=chassis)
txt('screen_carrier','NORTH  |  3G',.0020,loc=(-.014,.0502,.01241),material=ui_white,body=chassis)
txt('screen_clock','10:08',.0070,loc=(0,.040,.01241),material=ui_white,body=chassis)
txt('screen_date','MON  OCT 12',.0025,loc=(0,.032,.01241),material=ui_white,body=chassis)
for i in range(4):
    x=-.015+i*.010
    v4.box('app_tile_'+str(i),(.0065,.0065,.00012),(x,.020,.01236),bevel=.0008,material=(ui_blue if i%2==0 else ui_white),body=chassis)
# Earpiece at upper forehead, steel rim and dark mesh strip
v4.box('earpiece_recess',(.026,.0038,.0004),(0,.0544,.0118),bevel=.0012,material=black,body=chassis)
for i in range(13):
    x=-.0108+i*.0018
    v4.cylinder('earpiece_hole_'+str(i),.00030,.00012,(x,.0544,.01208),segments=12,material=metal,body=chassis)
v4.sphere('status_led',.00030,loc=(.018,.0542,.01225),segments=20,material=led,body=chassis)
# Microphone / speaker perforations on top and bottom edge
for i in range(5):
    x=(i-2)*.0026
    v4.cylinder('bottom_mic_'+str(i),.00042,.001,(x,-.0577,.0065),rot=(math.pi/2,0,0),segments=12,material=black,body=chassis)
# Branding below screen
txt('brand_wordmark','B L A C K B E R R Y',.0017,loc=(0,.007,.0126),material=legend_dim,body=chassis)
# Trackball retaining socket and rings; sphere is a separate 3-axis rotating body.
ball_y=0.0
v4.cylinder('trackball_socket',.0062,.0012,(0,ball_y,.0122),segments=48,material=black,body=chassis)
v4.torus('trackball_chrome_ring',.0052,.00062,(0,ball_y,.01315),material=chrome,body=chassis)
v4.torus('trackball_inner_gasket',.00425,.00023,(0,ball_y,.01323),material=black,body=chassis)
trackball=v4.body('trackball')
v4.sphere('polished_trackball',.00375,loc=(0,ball_y,.0133),segments=40,material=keylight,body=trackball)
v4.joint('trackball_spin','generic',chassis,trackball,origin=(0,ball_y,.0133),axis=(0,0,1),xdir=(1,0,0),dofs=[('rotX',None),('rotY',None),('rotZ',None)])
# Navigation and call control island. Each keycap has its own pressing motion.
# Tiny call/end controls frame the trackball.
funcs=[('call',-.0105,ball_y,'↗'),('menu',-.0105,ball_y-.007,'≡'),('back',.0105,ball_y-.0012,'‹'),('end',.0105,ball_y-.0082,'×')]
# Define the key grid once so the moving caps, joints, and matching openings share exact centers.
rows=[
    ('QWERTYUIOP',-.0240,0.0),
    ('ASDFGHJKL',-.0343,.0025),
    ('ZXCVBNM',-.0447,.0050),
]
letter_defs=[]
for row_idx,(letters,y,offset) in enumerate(rows):
    n=len(letters); pitch=.0057
    for j,ch in enumerate(letters):
        x=((j-(n-1)/2)*pitch+offset)*KEY_X_SCALE
        letter_defs.append((row_idx,ch,x,y+KEY_SHIFT_Y,j))
# Bottom controls are sized and spaced to stay within the flat deck.
bottom_widths=[.0049,.0049,.0049,.0049,.0180,.0049,.0049,.0049]
bottom_names=['search','shift','alt','dollar','space','period','comma','enter']
bottom_gap=.00055
bottom_x=[]
cursor=-(sum(bottom_widths)+(len(bottom_widths)-1)*bottom_gap)/2
for w in bottom_widths:
    bottom_x.append(cursor+w/2)
    cursor+=w+bottom_gap
bottom_defs=[(nm,x,w,-.055+KEY_SHIFT_Y) for nm,x,w in zip(bottom_names,bottom_x,bottom_widths)]

# Cut shallow blind key wells into the front deck. The necks have 1.5 mm of clear
# downward travel while a solid rear skin remains intact below each well.
hole_defs=[]
for _nm,x,y,_ch in funcs:
    hole_defs.append((x,y,.0094,.0059))
for row_idx,_ch,x,y,_j in letter_defs:
    hole_defs.append((x,y,.00555,.00535))
for nm,x,w,y in bottom_defs:
    hole_defs.append((x,y,w+.00025,.0050))
# Apply the shell's outer rounding before cutting the precise key openings.
bpy.ops.object.select_all(action='DESELECT')
main_shell.select_set(True)
bpy.context.view_layer.objects.active=main_shell
bpy.ops.object.modifier_apply(modifier='Bevel')
bm=bmesh.new()
for x,y,sx,sy in hole_defs:
    geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
    bmesh.ops.scale(bm,vec=Vector((sx,sy,.0025)),verts=geom)
    bmesh.ops.translate(bm,vec=Vector((x,y,.01115)),verts=geom)
# Small USB charging/data socket cut through the bottom edge, separate from the mic row.
geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
bmesh.ops.scale(bm,vec=Vector((.008,.0032,.0022)),verts=geom)
bmesh.ops.translate(bm,vec=Vector((.018,-.0574,.0068)),verts=geom)
# SIM tray aperture is a short side cut-out with the moving tray filling it at rest.
geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
bmesh.ops.scale(bm,vec=Vector((.0015,.0152,.00115)),verts=geom)
bmesh.ops.translate(bm,vec=Vector((-W/2+.0002,SIM_Y,SIM_Z)),verts=geom)
# Recess the display bezel into the front deck so only the glass and interface sit proud.
geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
bmesh.ops.scale(bm,vec=Vector((.0524,.0484,.00115)),verts=geom)
bmesh.ops.translate(bm,vec=Vector((0,.032,.011675)),verts=geom)
# Rebate for the flush rear cover: extend the cutter just beyond the rear plane so the
# cover face is cleanly exposed rather than coplanar with the unibody back skin.
geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
bmesh.ops.scale(bm,vec=Vector((.0574,.0644,.0012)),verts=geom)
bmesh.ops.translate(bm,vec=Vector((0,BATTERY_COVER_Y,.0018)),verts=geom)
# Deeper inset behind the cover leaves room for the battery pack.
geom=bmesh.ops.create_cube(bm,size=1.0)['verts']
bmesh.ops.scale(bm,vec=Vector((.048,.061,.0042)),verts=geom)
bmesh.ops.translate(bm,vec=Vector((0,BATTERY_COVER_Y,.0033)),verts=geom)
cutter_mesh=bpy.data.meshes.new('keyboard_slot_cutters_mesh')
bm.to_mesh(cutter_mesh); bm.free()
cutter=bpy.data.objects.new('keyboard_slot_cutters',cutter_mesh)
bpy.context.scene.collection.objects.link(cutter)
v4.boolean(main_shell,cutter)

for nm,x,y,ch in funcs:
    b=v4.body('key_function_'+nm)
    v4.box('key_function_stem_'+nm,(.0094,.0059,.0012),(x,y,.0122),bevel=.0002,material=black,body=b)
    v4.box('key_function_cap_'+nm,(.009,.0055,.00135),(x,y,.01285),bevel=.0013,material=keylight,body=b)
    dome=v4.sphere('key_function_dome_'+nm,.001,loc=(x,y,.01338),segments=32,material=keylight,body=b)
    dome.scale=(4.25,2.55,.47)
    icon=ch
    icon_mat=legend_dim
    if nm=='call': icon,icon_mat='☎',call_ink
    if nm=='end': icon,icon_mat='×',end_ink
    txt('key_function_legend_'+nm,icon,.0030,loc=(x,y,.01389),material=icon_mat,body=b)
    v4.joint('press_function_'+nm,'prismatic',chassis,b,origin=(x,y,.0130),axis=(0,0,1),limits=(-KEY_STROKE,0))
# Alphabet keys: all 26 letters in conventional QWERTY staggering. Four navigation keys
# plus eight bottom-row controls bring the complete moving keyboard to 38 keys.
key_index=0
for row_idx,ch,x,y,j in letter_defs:
    b=v4.body('key_%02d'%key_index)
    v4.box('key_neck_%02d'%key_index,(.00535,.00515,.0012),(x,y,.0122),bevel=.00015,material=black,body=b)
    v4.box('keycap_%02d'%key_index,(.0051,.0049,.0011),(x,y,.01275),bevel=.00065,material=keymat,body=b)
    dome=v4.sphere('key_dome_%02d'%key_index,.001,loc=(x,y,.01310),segments=24,material=keymat,body=b)
    dome.scale=(2.45,2.35,.30)
    txt('key_letter_%02d'%key_index,ch,.0030,loc=(x,y,.01336),material=legend,body=b)
    # Alternate digits are secondary legends, not a numeric keypad.
    alt='1234567890'[j] if row_idx==0 else ('!@#$%&*'[(j%7)] if row_idx==2 else '')
    if alt:
        txt('key_alt_%02d'%key_index,alt,.00145,loc=(x+.00155,y-.00150,.01336),material=legend_dim,body=b)
    v4.joint('press_key_%02d'%key_index,'prismatic',chassis,b,origin=(x,y,.0130),axis=(0,0,1),limits=(-KEY_STROKE,0))
    key_index+=1
# Bottom row: search, shift, alt, dollar, space, period, comma, and enter controls.
for nm,x,w,y in bottom_defs:
    b=v4.body('key_%02d'%key_index)
    v4.box('key_neck_'+nm,(w+.00025,.0050,.0012),(x,y,.0122),bevel=.00015,material=black,body=b)
    v4.box('keycap_'+nm,(w,.0052,.0011),(x,y,.01275),bevel=min(.00065,w*.16),material=(keylight if nm=='space' else keymat),body=b)
    label={'search':'⌕','shift':'SHIFT','alt':'ALT','dollar':'SYM','space':'','comma':',','period':'.','enter':'↵'}[nm]
    if label:
        txt('keylegend_'+nm,label,(.00125 if nm in ('shift','alt','dollar') else .0022),loc=(x,y,.01336),material=legend,body=b)
    else:
        txt('spacebar_mark','',.001,loc=(x,y,.01336),material=legend,body=b)
    v4.joint('press_key_%02d'%key_index,'prismatic',chassis,b,origin=(x,y,.0130),axis=(0,0,1),limits=(-KEY_STROKE,0))
    key_index+=1
# Battery bay rails anchor inside the 1 mm rear-cover rebate and support the slider.
for sx in (-1,1):
    v4.box('battery_rail_'+str(sx),(.0014,.062,.0008),(sx*.0260,BATTERY_COVER_Y,.0028),bevel=.0002,material=black,body=chassis)
# Dark gasket visible in the 0.2 mm rebate clearance outlines the closed back cover.
for sx in (-1,1):
    v4.box('battery_seam_side_'+str(sx),(.00020,.0640,.00007),(sx*.02860,BATTERY_COVER_Y,.001435),bevel=.000035,material=black,body=chassis)
for sy in (-1,1):
    v4.box('battery_seam_end_'+str(sy),(.0572,.00020,.00007),(0,BATTERY_COVER_Y+sy*.03210,.001435),bevel=.000035,material=black,body=chassis)
# USB edge opening has a narrow satin lip and a dark recessed connector face.
v4.box('usb_port_bezel',(.0090,.0009,.0028),(.018,-.0578,.0068),bevel=.00065,material=port_metal,body=chassis)
v4.box('usb_port_recess',(.0070,.0010,.0017),(.018,-.05815,.0068),bevel=.00048,material=black,body=chassis)
# inset well visible when cover slides; discrete battery silhouette and contacts.
v4.box('battery_well',(.046,.059,.00010),(0,BATTERY_COVER_Y,.00535),bevel=.0001,material=black,body=chassis)
v4.box('battery_pack',(.044,.053,.0024),(0,BATTERY_COVER_Y,.0039),bevel=.0008,material=shell2,body=chassis)
for i in range(3):
    v4.box('battery_contact_'+str(i),(.002,.004,.00012),(-.010+i*.010,BATTERY_COVER_Y+.025,.00516),bevel=.0001,material=metal,body=chassis)
# Back cover slides toward -Y along side rails. Cover dimensions stay inside handset outline at rest.
battery=v4.body('battery_cover')
v4.box('rear_battery_cover',(.057,.064,.0010),(0,BATTERY_COVER_Y,BATTERY_COVER_Z),bevel=.0020,material=covermat,body=battery)
# molded anti-slip ribs, seam/latch details move with cover
for i in range(7):
    yy=-.045+i*.0062+BATTERY_SHIFT_Y
    v4.box('cover_grip_rib_'+str(i),(.030,.00075,.00012),(0,yy,.00134),bevel=.00006,material=shell,body=battery)
# Thumb notch with a fine polished lip, set near the cover's upper edge.
v4.box('cover_thumb_lip',(.014,.0036,.00012),(0,.0094,.00134),bevel=.0013,material=metal,body=battery)
v4.box('cover_thumb_recess',(.0105,.0021,.00012),(0,.0094,.00124),bevel=.00095,material=black,body=battery)
txt('cover_label','3.7V  1500mAh',.0020,loc=(0,-.007+BATTERY_SHIFT_Y,.00124),rot=(math.pi,0,0),material=legend_dim,body=battery)
v4.joint('battery_slide','prismatic',chassis,battery,origin=(0,BATTERY_COVER_Y,BATTERY_COVER_Z),axis=(0,-1,0),limits=(0,.018))
# SIM card tray reaches 15 mm into its side guide; at full extension 6 mm stays captured.
sim=v4.body('sim_tray')
SIM_X = -.0240
v4.box('sim_tray_plate',(.015,.015,.0009),(SIM_X,SIM_Y,SIM_Z),bevel=.00035,material=metal,body=sim)
v4.box('sim_slot_lip',(.00020,.0158,.0012),(-W/2-.00010,SIM_Y,SIM_Z),bevel=.00025,material=black,body=chassis)
v4.box('sim_pull_notch',(.0012,.004,.00065),(-.0312,SIM_Y,SIM_Z),bevel=.0003,material=black,body=sim)
txt('sim_mark','SIM',.0017,loc=(SIM_X,SIM_Y,.00730),rot=(0,0,math.pi/2),material=legend_dim,body=sim)
v4.joint('sim_slide','prismatic',chassis,sim,origin=(SIM_X,SIM_Y,SIM_Z),axis=(-1,0,0),limits=(0,.009))
# Rear camera/flash at top, with coaxial-looking lens stack and mic port.
v4.cylinder('camera_gasket',.0040,.00075,(0,.049,.00115),segments=40,material=black,body=chassis)
v4.cylinder('camera_metal_rim',.00335,.00065,(0,.049,.00078),segments=40,material=metal,body=chassis)
v4.cylinder('camera_lens',.00255,.00045,(0,.049,.00040),segments=40,material=glass,body=chassis)
v4.sphere('camera_lens_glint',.00125,loc=(0,.049,.00028),segments=24,material=ui_blue,body=chassis)
v4.box('camera_flash',(.0035,.004,.0007),(.008,.049,.00105),bevel=.0014,material=legend,body=chassis)
txt('rear_model_mark','QWERTY  |  3G',.0023,loc=(0,.010,.00144),rot=(math.pi,0,0),material=legend_dim,body=chassis)
# two tiny chassis screws on battery bay corners
for sx in (-1,1):
    for yy in (-.050,.001):
        v4.cylinder('rear_screw',.0008,.00035,(sx*.025,yy,.0018),segments=16,material=metal,body=chassis)

assert key_index == 34, key_index
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend; keys=',key_index)
