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

v4.reset()

def annular_hex(name, radius, inner_radius, depth, loc, material, body):
    """Closed hexagonal compression nut with a real central cable bore."""
    bm = bmesh.new()
    outer = []
    for side in range(6):
        a0 = math.radians(30 + side*60)
        a1 = math.radians(30 + (side+1)*60)
        p0=(radius*math.cos(a0), radius*math.sin(a0))
        p1=(radius*math.cos(a1), radius*math.sin(a1))
        for j in range(4):
            t=j/4
            outer.append((p0[0]*(1-t)+p1[0]*t,p0[1]*(1-t)+p1[1]*t))
    n=len(outer); lower=[]; upper=[]; hole_lower=[]; hole_upper=[]
    for i,(x,y) in enumerate(outer):
        a=2*math.pi*i/n
        lower.append(bm.verts.new((x,y,0)))
        upper.append(bm.verts.new((x,y,depth)))
        hole_lower.append(bm.verts.new((inner_radius*math.cos(a),inner_radius*math.sin(a),0)))
        hole_upper.append(bm.verts.new((inner_radius*math.cos(a),inner_radius*math.sin(a),depth)))
    for i in range(n):
        j=(i+1)%n
        bm.faces.new((lower[i],lower[j],hole_lower[j],hole_lower[i]))
        bm.faces.new((upper[i],hole_upper[i],hole_upper[j],upper[j]))
        bm.faces.new((lower[i],upper[i],upper[j],lower[j]))
        bm.faces.new((hole_lower[i],hole_lower[j],hole_upper[j],hole_upper[i]))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me=bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
    ob=bpy.data.objects.new(name,me); v4._link(ob)
    ob.location=loc
    v4._finish(ob,body,material,bevel=0.0003,smooth=False)
    return ob
# Materials: common industrial electrical enclosure finishes.
shell = v4.plastic('warm_light_grey_polycarbonate', (0.72, 0.74, 0.72), roughness=0.38, texture=0.10)
cover_mat = v4.plastic('cover_light_grey_polycarbonate', (0.79, 0.80, 0.77), roughness=0.34, texture=0.10)
inner = v4.plastic('mounting_plate_pale_grey', (0.84, 0.83, 0.77), roughness=0.48, texture=0.08)
black = v4.rubber('gasket_black', (0.055, 0.06, 0.055), roughness=0.8)
steel = v4.metal('zinc_plated_steel', (0.67, 0.69, 0.70), roughness=0.32, brushed=False)
steel_dark = v4.metal('dark_zinc_steel', (0.38, 0.41, 0.42), roughness=0.38, brushed=False)
blue = v4.plastic('terminal_blue', (0.10, 0.30, 0.67), roughness=0.38, texture=0.08)
grey_terminal = v4.plastic('terminal_grey', (0.57, 0.59, 0.57), roughness=0.4, texture=0.08)
green = v4.plastic('earth_terminal_green', (0.16, 0.52, 0.25), roughness=0.4, texture=0.08)
yellow = v4.plastic('earth_yellow', (0.92, 0.73, 0.08), roughness=0.4, texture=0.08)
white = v4.mat('marking_white', (0.94, 0.94, 0.90), roughness=0.5)
textmat = v4.mat('dark_legend_ink', (0.10, 0.12, 0.12), roughness=0.55)

# Overall envelope: 300 x 240 x 110 mm. Front faces -Y.
W, H, D = 0.300, 0.240, 0.110
wall = 0.004
base = v4.body('back_box')
# Open-front molded shell, with meeting wall edges and a rear skin.
v4.box('rear_wall', (W, 0.006, H), (0, 0.052, 0), bevel=0.004, material=shell, body=base)
for sx, label in [(-1, 'left'), (1, 'right')]:
    v4.box('side_wall_'+label, (wall, 0.102, H-0.008), (sx*(W/2-wall/2), -0.001, 0), bevel=0.0025, material=shell, body=base)
for sz, label in [(-1, 'bottom'), (1, 'top')]:
    v4.box('wall_'+label, (W-2*wall, 0.102, wall), (0, -0.001, sz*(H/2-wall/2)), bevel=0.002, material=shell, body=base)
# Inner mounting plate, four molded stand-offs and corner fixing recesses.
v4.box('interior_mounting_plate', (0.270, 0.003, 0.210), (0, 0.043, 0), bevel=0.003, material=inner, body=base)
for x in (-0.125, 0.125):
    for z in (-0.095, 0.095):
        v4.cylinder('mounting_boss', 0.009, 0.012, (x, 0.045, z), rot=(math.pi/2,0,0), material=shell, body=base)
        v4.cylinder('mounting_boss_recess', 0.003, 0.001, (x, 0.0405, z), rot=(math.pi/2,0,0), segments=16, material=steel_dark, body=base)
# DIN rail with folded shoulders, lips and screw heads.
rail_y = 0.012
v4.box('din_rail_web', (0.220, 0.003, 0.035), (0, rail_y, 0.006), bevel=0.001, material=steel, body=base)
v4.box('din_rail_top_lip', (0.220, 0.006, 0.004), (0, rail_y-0.002, 0.0255), bevel=0.0008, material=steel, body=base)
v4.box('din_rail_bottom_lip', (0.220, 0.006, 0.004), (0, rail_y-0.002, -0.0135), bevel=0.0008, material=steel, body=base)
for x in (-0.098, 0.098):
    v4.cylinder('rail_fixing_screw', 0.0032, 0.0015, (x, rail_y-0.0024, 0.006), rot=(math.pi/2,0,0), segments=16, material=steel_dark, body=base)
# Two molded standoffs bridge the rear mounting plate to the DIN rail web.
for x in (-0.103, 0.103):
    v4.box('din_rail_standoff', (0.012, 0.028, 0.014), (x, 0.0275, 0.006), bevel=0.001, material=steel_dark, body=base)
# Six DIN terminal blocks. Individual clamp housings, top screw wells, conductor ports and small legends.
term_xs = [-0.082, -0.049, -0.016, 0.017, 0.050, 0.083]
term_mats = [grey_terminal, blue, grey_terminal, blue, grey_terminal, green]
for i, (x, tm) in enumerate(zip(term_xs, term_mats)):
    v4.box('terminal_%02d_housing'%i, (0.030, 0.030, 0.045), (x, -0.006, 0.016), bevel=0.003, material=tm, body=base)
    v4.box('terminal_%02d_top_bridge'%i, (0.024, 0.019, 0.004), (x, -0.007, 0.0405), bevel=0.0015, material=steel, body=base)
    v4.cylinder('terminal_%02d_clamp_screw'%i, 0.0042, 0.002, (x, -0.008, 0.0435), rot=(0,0,0), segments=20, material=steel_dark, body=base)
    # paired front wire entry ferrules and dark bores
    for z in (0.007, 0.025):
        v4.cylinder('terminal_%02d_wire_ferrule'%i, 0.0045, 0.002, (x, -0.0222, z), rot=(math.pi/2,0,0), segments=20, material=steel, body=base)
        v4.cylinder('terminal_%02d_wire_bore'%i, 0.0023, 0.0021, (x, -0.0233, z), rot=(math.pi/2,0,0), segments=16, material=black, body=base)
# Green/yellow earth marking at the last terminal and rail end stops.
v4.box('earth_stripe_yellow', (0.010, 0.001, 0.003), (0.083, -0.0231, 0.033), bevel=0, material=yellow, body=base)
for x in (-0.116, 0.116):
    v4.box('rail_end_stop', (0.007, 0.022, 0.043), (math.copysign(0.114, x), -0.004, 0.016), bevel=0.001, material=steel, body=base)
# Fixed keeper tab on the inside of the right wall catches the latch cam at its closed orientation.
v4.box('latch_keeper', (0.014, 0.003, 0.006), (0.139, -0.0475, 0.006), bevel=0.001, material=steel, body=base)
# Bottom wall cable glands: fixed seats meet wall; rotating compression nuts are distinct bodies.
gland_xs = (-0.073, 0.073)
for i, x in enumerate(gland_xs):
    # molded seat and compression shoulder, with strain-relief neck projecting below box
    v4.cylinder('gland_seat_%d'%i, 0.020, 0.008, (x, 0.0, -0.119), material=black, body=base)
    v4.cylinder('gland_fixed_shoulder_%d'%i, 0.016, 0.012, (x, 0.0, -0.128), material=shell, body=base)
    v4.cylinder('gland_threaded_neck_%d'%i, 0.011, 0.012, (x, 0.0, -0.140), material=black, body=base)
    v4.torus('gland_seal_bead_%d'%i, 0.014, 0.0013, (x, 0.0, -0.133), material=shell, body=base)
    # cable stem enters at the opening and extends below the compression nut
    v4.cylinder('cable_stem_%d'%i, 0.006, 0.034, (x, 0.0, -0.161), material=black, body=base)
    ring = v4.body('gland_ring_left' if i == 0 else 'gland_ring_right')
    # Hex compression nut extruded along Z; flattened orientation gives recognizable wrench faces.
    pts = [(0.014*math.cos(math.radians(30+60*k)), 0.014*math.sin(math.radians(30+60*k))) for k in range(6)]
    annular_hex('compression_hex_nut_%d'%i, 0.014, 0.0072, 0.010, (x,0,-0.158), steel, ring)
    annular_hex('compression_grip_band_%d'%i, 0.012, 0.0072, 0.009, (x,0,-0.167), shell, ring)
    v4.torus('compression_rib_%d'%i, 0.0115, 0.0008, (x,0,-0.1655), material=shell, body=ring)
    v4.joint('gland_left_turn' if i == 0 else 'gland_right_turn', 'continuous', base, ring,
             origin=(x,0,-0.147), axis=(0,0,1))
# cover hinged along the left vertical front edge.
cover = v4.body('cover')
# Front lid overlays the front rim by 5 mm around all edges.
cover_panel=v4.box('cover_outer_panel', (0.310, 0.006, 0.250), (0, -0.058, 0), bevel=0.006, material=cover_mat, body=cover)
# Clearance bore lets the captive spindle connect to its rear cam without crossing the panel.
latch_bore=v4.box('temporary_latch_bore', (0.008, 0.012, 0.008), (0.112, -0.058, 0), bevel=0, material=None)
v4.boolean(cover_panel, latch_bore)
# Backside perimeter gasket follows the opening and compresses against the rim.
for z in (-0.113, 0.113):
    v4.box('cover_gasket_horizontal', (0.280, 0.002, 0.003), (0, -0.052, z), bevel=0.001, material=black, body=cover)
for x in (-0.138, 0.138):
    v4.box('cover_gasket_vertical', (0.003, 0.002, 0.222), (x, -0.052, 0), bevel=0.001, material=black, body=cover)
# Subtle molded outer inset border and hinge knuckles.
for z in (-0.106, 0.106):
    v4.box('cover_molded_border_h', (0.254, 0.0015, 0.0015), (0.012, -0.0618, z), bevel=0.0007, material=shell, body=cover)
for x in (-0.126, 0.150):
    v4.box('cover_molded_border_v', (0.0015, 0.0015, 0.210), (x, -0.0618, 0), bevel=0.0007, material=shell, body=cover)
hinge_x, hinge_y = -0.155, -0.050
# hinge leaves on shell and door; three separated knuckles around a common steel pin
for k, z in enumerate((-0.078, 0.0, 0.078)):
    v4.cylinder('hinge_knuckle_%d'%k, 0.0055, 0.052, (hinge_x, hinge_y, z), material=steel, body=cover if k != 1 else base)
    v4.cylinder('hinge_pin_end_%d'%k, 0.0021, 0.003, (hinge_x, hinge_y, z + (-0.027 if k != 1 else 0.027)), material=steel_dark, body=base)
# Leaves to the enclosure and cover approach the barrels and are fastened with visible screws.
v4.box('hinge_fixed_leaf_upper', (0.012,0.002,0.050), (-0.148,-0.049,0.078), bevel=0.0007, material=steel, body=base)
v4.box('hinge_fixed_leaf_lower', (0.012,0.002,0.050), (-0.148,-0.049,-0.078), bevel=0.0007, material=steel, body=base)
v4.box('hinge_cover_leaf_middle', (0.012,0.002,0.050), (-0.145,-0.049,0), bevel=0.0007, material=steel, body=cover)
for z in (-0.078, 0.078):
    v4.cylinder('hinge_leaf_screw', 0.0028, 0.0015, (-0.148,-0.0505,z), rot=(math.pi/2,0,0), segments=16, material=steel_dark, body=base)
v4.joint('cover_hinge', 'revolute', base, cover, origin=(hinge_x,hinge_y,0), axis=(0,0,1), limits=(-math.radians(110),0))
# Outer latch bezel fixed to cover and captive quarter-turn screw on its own pivot.
latch_x, latch_y = 0.112, -0.062
v4.torus('latch_bezel_ring', 0.0105, 0.003, (latch_x, -0.063, 0), rot=(math.pi/2,0,0), material=steel, body=cover)
latch = v4.body('latch_screw')
# Captive spindle passes through the cover bore; its rear cam catches the fixed keeper.
v4.cylinder('captive_screw_shaft', 0.0034, 0.017, (latch_x,-0.055,0), rot=(math.pi/2,0,0), material=steel_dark, body=latch)
v4.cylinder('quarter_turn_head', 0.0082, 0.004, (latch_x,-0.0655,0), rot=(math.pi/2,0,0), material=steel, body=latch)
v4.box('latch_head_slot', (0.010,0.001,0.0015), (latch_x,-0.0677,0), bevel=0.0004, material=black, body=latch)
v4.box('latch_cam_tongue', (0.030,0.003,0.005), (latch_x+0.015,-0.043,0), bevel=0.0008, material=steel_dark, body=latch)
v4.joint('latch_turn','revolute',cover,latch,origin=(latch_x,-0.064,0),axis=(0,-1,0),limits=(0,math.pi/2))
# Front identification and electrical warning marks, raised/printed onto the lid.
v4.box('rating_label', (0.078,0.0012,0.027), (0.020,-0.0622,0.070), bevel=0.001, material=white, body=cover)
v4.text('rating_text','JUNCTION BOX',0.006,loc=(-0.014,-0.0631,0.070),rot=(math.pi/2,0,0),extrude_depth=0.00025,material=textmat,body=cover)
v4.text('voltage_text','IP65  |  400 V',0.005,loc=(-0.011,-0.0631,0.061),rot=(math.pi/2,0,0),extrude_depth=0.0002,material=textmat,body=cover)
# Small molded warning triangle and lightning bolt symbol at lower right.
v4.extrude('warning_triangle', [(0,0),(0.010,0),(0.005,0.009)], 0.0007, loc=(0.105,-0.0624,-0.083), rot=(math.pi/2,0,0), bevel=0.0003, material=yellow, body=cover)
v4.text('warning_bolt','!',0.007,loc=(0.108,-0.0633,-0.082),rot=(math.pi/2,0,0),extrude_depth=0.0002,material=textmat,body=cover)
# Minimal branding panel along lower edge.
v4.text('molded_series','ELECTRICAL ENCLOSURE  •  300 x 240',0.0048,loc=(-0.065,-0.0622,-0.101),rot=(math.pi/2,0,0),extrude_depth=0.00015,material=textmat,body=cover)

# Apply bevels so the exported mesh has welded edge topology for all rigid assemblies.
for ob in list(v4.asset_objects()):
    bevel_mods=[m.name for m in ob.modifiers if m.type=='BEVEL']
    if bevel_mods:
        bpy.context.view_layer.objects.active=ob
        ob.select_set(True)
        for mod_name in bevel_mods:
            bpy.ops.object.modifier_apply(modifier=mod_name)
        ob.select_set(False)

v4.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'asset.blend'))
print('saved asset.blend')
