import math
import os
import random
import sys

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

v4.reset()

# Materials
black = v4.plastic("charcoal_abs", (0.025, 0.032, 0.038), roughness=0.3, texture=0.08)
black_soft = v4.rubber("silicone_seal", (0.012, 0.018, 0.022), roughness=0.72)
steel = v4.metal("hinge_stainless", (0.67, 0.72, 0.75), roughness=0.28, brushed=True)
glass = v4.glass("low_iron_glass", (0.88, 0.96, 0.99), roughness=0.035)
water = v4.glass("aquarium_water", (0.78, 0.91, 0.94), roughness=0.012)
water.node_tree.nodes["Principled BSDF"].inputs["IOR"].default_value = 1.333
smoke = v4.plastic("smoked_polycarbonate", (0.13, 0.16, 0.17), roughness=0.34, texture=0.06)
white = v4.plastic("light_diffuser", (0.91, 0.87, 0.71), roughness=0.32, texture=0.03)
led = v4.emissive("warm_led", (1.0, 0.76, 0.42), strength=1.4)
gravel_base = v4.plastic("fine_gravel_bed", (0.16, 0.17, 0.15), roughness=0.96, texture=0.48)
gravel_mats = [v4.mat("gravel_slate", (0.12, 0.15, 0.16), roughness=0.86),
               v4.mat("gravel_sandstone", (0.37, 0.31, 0.23), roughness=0.9),
               v4.mat("gravel_charcoal", (0.055, 0.07, 0.075), roughness=0.9)]
rock = v4.mat("river_stone", (0.31, 0.34, 0.31), roughness=0.86)
green = v4.mat("aquatic_leaf", (0.055, 0.29, 0.12), roughness=0.58)
green2 = v4.mat("aquatic_leaf_light", (0.12, 0.39, 0.17), roughness=0.56)
filter_mat = v4.plastic("filter_dark_gray", (0.09, 0.12, 0.14), roughness=0.4, texture=0.1)

# Overall 60 x 30 x 39 cm glass body, base trim included.
W, D = 0.600, 0.300
z_base_top = 0.025
z_top = 0.405
wall_t = 0.006
rim_z = 0.405
rim_h = 0.020
lid_bottom = 0.425

fixed = v4.body("tank")

# Molded lower frame with a broad foot lip and vertical corner reinforcement.
v4.box("lower_plinth", (W + 0.008, D + 0.008, 0.025), (0, 0, 0.0125), bevel=0.004, material=black, body=fixed)
v4.box("front_base_bead", (W - 0.014, 0.006, 0.010), (0, -D / 2 - 0.006, 0.019), bevel=0.002, material=black, body=fixed)
v4.box("rear_base_bead", (W - 0.014, 0.006, 0.010), (0, D / 2 + 0.006, 0.019), bevel=0.002, material=black, body=fixed)

# Glass tank: bottom rests directly on the base, walls butt against bottom and each other.
v4.box("glass_bottom", (W - 0.012, D - 0.012, wall_t), (0, 0, z_base_top + wall_t/2), bevel=0.0007, material=glass, body=fixed)
wall_h = z_top - z_base_top - wall_t
wall_z = z_base_top + wall_t + wall_h/2
v4.box("glass_front", (W - 2*wall_t, wall_t, wall_h), (0, -D/2 + wall_t/2, wall_z), bevel=0.0006, material=glass, body=fixed)
v4.box("glass_back", (W - 2*wall_t, wall_t, wall_h), (0, D/2 - wall_t/2, wall_z), bevel=0.0006, material=glass, body=fixed)
side_d = D - 2*wall_t
for sx, nm in [(-1, "left"), (1, "right")]:
    v4.box(f"glass_{nm}", (wall_t, side_d, wall_h), (sx*(W/2-wall_t/2), 0, wall_z), bevel=0.0006, material=glass, body=fixed)

# Discreet corner silicone beads, close to panel seams.
for sx in (-1, 1):
    for sy in (-1, 1):
        v4.box(f"silicone_corner_{sx}_{sy}", (0.004, 0.004, wall_h-0.012),
               (sx*(W/2-wall_t-0.002), sy*(D/2-wall_t-0.002), wall_z), bevel=0.0015, material=black_soft, body=fixed)

# Four-piece molded top rim frame; individual rails form a continuous, flush collar.
rail_h = rim_h
rail_zc = rim_z + rail_h/2
rail_w = 0.024
v4.box("rim_front", (W+0.004, rail_w, rail_h), (0, -D/2+rail_w/2, rail_zc), bevel=0.003, material=black, body=fixed)
v4.box("rim_back", (W+0.004, rail_w, rail_h), (0, D/2-rail_w/2, rail_zc), bevel=0.003, material=black, body=fixed)
for sx, nm in [(-1,"left"),(1,"right")]:
    v4.box(f"rim_{nm}", (rail_w, D-2*rail_w, rail_h), (sx*(W/2-rail_w/2), 0, rail_zc), bevel=0.003, material=black, body=fixed)
# Inset inner ledge, top face sits flush with rim rails.
v4.box("rim_front_inner_lip", (W-2*rail_w, 0.008, 0.004), (0, -D/2+rail_w+0.004, rim_z+rail_h-0.002), bevel=0.001, material=black, body=fixed)
v4.box("rim_back_inner_lip", (W-2*rail_w, 0.008, 0.004), (0, D/2-rail_w-0.004, rim_z+rail_h-0.002), bevel=0.001, material=black, body=fixed)

# Hinge brackets and pin supports are part of the fixed rim assembly.
hx = 0.205
hy = D/2 + 0.002  # unchanged hinge-axis position
hz = lid_bottom
for i, x in enumerate((-hx, hx)):
    # Low profile raised mounting saddle and upright cheek around the hinge line.
    v4.box(f"hinge_saddle_{i}", (0.048, 0.030, 0.006), (x, hy-0.004, rim_z+rail_h-0.004), bevel=0.0015, material=black, body=fixed)
    # Split support cheeks sit just outside each end of the moving sleeve.
    for side in (-1, 1):
        cheek_x = x + side*0.027
        v4.box(f"hinge_cheek_{i}_{side}", (0.008, 0.018, 0.014), (cheek_x, hy+0.012, hz+0.0055), bevel=0.0015, material=black, body=fixed)
    # Silver pin heads bridge the 1 mm running clearance between barrel ends and cheeks.
    for side in (-1, 1):
        cap_x = x + side*0.0225
        v4.cylinder(f"fixed_hinge_pin_head_{i}_{side}", 0.0045, 0.001, (cap_x, hy, hz+0.006),
                    rot=(0, math.pi/2, 0), segments=28, bevel=0.0002, material=steel, body=fixed)
    for s in (-1, 1):
        v4.cylinder(f"hinge_screw_{i}_{s}", 0.0026, 0.0015, (x+s*0.016, hy-0.010, rim_z+rail_h+0.004), rot=(math.pi/2,0,0), segments=20, bevel=0.0002, material=steel, body=fixed)

# Interior bed and a decorative, restrained freshwater layout.
# Gravel bed is under the filter intake and visible through the front pane.
v4.box("gravel_bed", (W-0.045, D-0.050, 0.030), (0, 0, 0.047), bevel=0.012, material=gravel_base, body=fixed)
# Fine gravel over the substrate; small stones are partly embedded so they remain attached.
rng = random.Random(60412)
for i in range(168):
    x = rng.uniform(-0.265, 0.265)
    y = rng.uniform(-0.116, 0.116)
    r = rng.uniform(0.0038, 0.0070)
    stone = v4.sphere(f"fine_gravel_{i:02d}", 1.0, (x,y,0.061), segments=12,
                      material=gravel_mats[rng.randrange(len(gravel_mats))], body=fixed)
    stone.scale = (r, r*rng.uniform(0.68,0.96), r*rng.uniform(0.38,0.62))
# Three smooth river stones add a larger scale contrast without dominating the bed.
for i,(x,y,sx,sy,sz) in enumerate([(-.13,.04,.030,.021,.016),(.13,.055,.026,.019,.013),(.225,-.065,.022,.017,.013)]):
    v4.sphere(f"river_rock_{i}", 1.0, (x,y,.062), segments=24, material=rock, body=fixed).scale=(sx,sy,sz)

# Fine-leaved aquatic stems: 8–11 slender, curved blades per clump with varied reach.
plant_specs = [(-.205,-.020,16,.12,.22),(.215,.025,15,.10,.20),(-.020,.070,13,.09,.17)]
for pi,(bx,by,count,hlo,hhi) in enumerate(plant_specs):
    for j in range(count):
        a=2*math.pi*j/count + 0.17*pi
        h=rng.uniform(hlo,hhi)
        sway=rng.uniform(.018,.048)
        side=rng.uniform(-.012,.012)
        start=(bx+rng.uniform(-.008,.008), by+rng.uniform(-.008,.008), .056)
        pts=[start,
             (start[0]+math.cos(a)*sway*.22, start[1]+math.sin(a)*sway*.22, .056+h*.34),
             (start[0]+math.cos(a)*sway*.72+side*.4, start[1]+math.sin(a)*sway*.72-side*.2, .056+h*.72),
             (start[0]+math.cos(a)*sway+side, start[1]+math.sin(a)*sway-side*.4, .056+h)]
        v4.tube(f"plant_blade_{pi}_{j}", pts, rng.uniform(.0010,.00145), material=green2 if j%3==0 else green,
                body=fixed, resolution=8)

# Water fills the tank to 28 mm below the top rim; the volume meets the panes and gravel bed.
water_top = 0.397
water_bottom = 0.060
v4.box("water_volume", (W-2*wall_t+0.002, D-2*wall_t+0.002, water_top-water_bottom),
       (0,0,(water_top+water_bottom)/2), bevel=0.001, material=water, body=fixed)

# Hang-on-back filter body sits outside the rear glass; its molded hook straddles the rim.
fx, fy = 0.000, 0.184
v4.box("filter_body", (0.066, 0.060, 0.125), (fx,fy,0.323), bevel=0.009, material=filter_mat, body=fixed)
v4.box("filter_top_cap", (0.070,0.064,0.014), (fx,fy,0.3925), bevel=0.004, material=black, body=fixed)
# Molded U hook rises over the rear trim and returns down behind the tank wall.
v4.tube("filter_rim_hook", [(fx,0.157,0.365),(fx,0.153,0.386),(fx,0.151,0.411),
                            (fx,0.151,0.425),(fx,0.160,0.431),(fx,0.173,0.431),
                            (fx,0.180,0.423),(fx,0.181,0.397),(fx,0.181,0.384)],
        0.0035, material=black, body=fixed, resolution=12)
# Outlet channel projects over the rim into the tank; shallow end lip makes the return visible.
v4.box("filter_outflow_channel", (0.050,0.070,0.008), (fx,0.121,0.407), bevel=0.002, material=filter_mat, body=fixed)
v4.box("filter_outflow_lip", (0.050,0.006,0.012), (fx,0.086,0.407), bevel=0.002, material=black, body=fixed)
# Slotted grille and stepped intake tube are inside the water, connected to the outer motor housing.
for k in range(5):
    z=.300+k*.014
    v4.box(f"filter_outlet_slot_{k}", (0.034,0.0015,0.0035), (fx,0.153,z), bevel=0.0008, material=black_soft, body=fixed)
v4.cylinder("filter_intake", 0.0048, 0.300, (fx-0.012,0.112,0.190), segments=24, bevel=0.0005, material=filter_mat, body=fixed)
# Intake strainer rests just above the substrate and has molded horizontal slots.
v4.cylinder("intake_strainer",0.008,0.040,(fx-0.012,0.112,0.055),segments=24,bevel=0.001,material=black,body=fixed)
for z in (.042,.050,.058,.066,.074):
    v4.torus(f"intake_guard_{int(z*1000)}", 0.007, 0.001, (fx-0.012,0.112,z), segments=20, ring_segments=8, material=filter_mat, body=fixed)
# A short hose elbow links the intake to the filter's internal pump inlet.
v4.tube("filter_intake_elbow", [(fx-0.012,0.112,.335),(fx-0.012,0.130,.357),(fx,0.154,.367)],
        .004, material=filter_mat, body=fixed, resolution=10)

# Front badge and restrained level mark, both fixed to the front trim.
v4.box("brand_badge", (0.095,0.0018,0.010), (0,-D/2-0.004,0.014), bevel=0.0015, material=black, body=fixed)

# Lid is one moving rigid body: framed smoked panel, LED bar, diffuser and hardware knuckles.
lid = v4.body("lid")
# Perimeter rails surround a thin smoked center panel.
lid_w, lid_d = W+0.004, D+0.004
frame = 0.018
v4.box("lid_front_rail", (lid_w, frame+0.004, 0.012), (0,-lid_d/2+frame/2,lid_bottom+0.006), bevel=0.003, material=black, body=lid)
back_seg_w = (lid_w-0.100)/2
back_seg_x = (0.100+back_seg_w)/2
for side,nm in [(-1,"left"),(1,"right")]:
    v4.box(f"lid_back_rail_{nm}", (back_seg_w, frame+0.004, 0.012),
           (side*back_seg_x,lid_d/2-frame/2,lid_bottom+0.006), bevel=0.003, material=black, body=lid)
for sx,nm in [(-1,"left"),(1,"right")]:
    v4.box(f"lid_{nm}_rail", (frame+0.004,lid_d-2*frame+0.004,0.012), (sx*(lid_w/2-frame/2),0,lid_bottom+0.006), bevel=0.003, material=black, body=lid)
# Rear-center relief clears the external filter hook; overlapping panel sections keep one continuous hood.
panel_w = lid_w-2*frame+0.004
panel_d = lid_d-2*frame+0.004
notch_w = 0.100
notch_depth = 0.031
front_d = panel_d-notch_depth
front_y = -panel_d/2+front_d/2
v4.box("lid_smoked_front_panel", (panel_w,front_d+0.002,0.003), (0,front_y,lid_bottom+0.006), bevel=0.0008, material=smoke, body=lid)
wing_w = (panel_w-notch_w)/2
wing_x = (notch_w+wing_w)/2
wing_d = notch_depth+0.002
wing_y = panel_d/2-wing_d/2
for side in (-1,1):
    v4.box(f"lid_smoked_rear_wing_{side}", (wing_w,wing_d,0.003), (side*wing_x,wing_y,lid_bottom+0.006),
           bevel=0.0008, material=smoke, body=lid)
# Small molded grip recess lip on front rail.
v4.box("lid_lift_tab", (0.072,0.020,0.014), (0,-lid_d/2-0.003,lid_bottom+0.006), bevel=0.004, material=black, body=lid)
# Light bar under the lid, set toward the front half to illuminate the tank.
v4.box("led_housing", (0.42,0.024,0.016), (0,-0.045,lid_bottom-0.003), bevel=0.005, material=black, body=lid)
v4.box("led_diffuser", (0.39,0.018,0.004), (0,-0.045,lid_bottom-0.015), bevel=0.003, material=white, body=lid)
v4.box("continuous_led_strip", (0.36,0.010,0.0015), (0,-0.045,lid_bottom-0.0177), bevel=0.002, material=led, body=lid)
# Small framed feeding hatch and two molded hinge details, all integrated with the lid body.
v4.box("feeding_hatch_frame", (0.112,0.080,0.011), (-0.205,-0.070,lid_bottom+0.011), bevel=0.002, material=black, body=lid)
v4.box("feeding_hatch_panel", (0.096,0.064,0.008), (-0.205,-0.070,lid_bottom+0.019), bevel=0.0015, material=smoke, body=lid)
for xx in (-0.245,-0.165):
    v4.cylinder(f"feeding_hatch_fastener_{int(xx*1000)}",0.0018,0.002, (xx,-0.070,lid_bottom+0.0215), segments=16, bevel=0.0002, material=steel, body=lid)
# Rear hinge sleeves sit around the fixed pin line; their bores are represented by metal collars.
for i,x in enumerate((-hx,hx)):
    v4.cylinder(f"lid_hinge_knuckle_{i}", 0.0068, 0.044, (x,hy,lid_bottom+0.006), rot=(0,math.pi/2,0), segments=32, bevel=0.0008, material=black, body=lid)

# Simple end indicator/button at one rear corner.


v4.joint("lid_hinge", "revolute", fixed, lid, origin=(0,hy,lid_bottom+0.006), axis=(1,0,0),
         limits=(-math.radians(105),0))

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