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

v4.reset()

# Warm, lightly grained beech with darker end-grain and restrained brass hardware.
wood = v4.wood("honey_beech", light=(0.65, 0.46, 0.27), dark=(0.50, 0.32, 0.18), grain_scale=8, roughness=0.70, coat=0.03)
frontwood = v4.wood("front_beech", light=(0.62, 0.42, 0.24), dark=(0.48, 0.29, 0.16), grain_scale=9, roughness=0.72, coat=0.03)
lidwood = v4.wood("lid_beech", light=(0.69, 0.49, 0.29), dark=(0.54, 0.35, 0.19), grain_scale=8, roughness=0.70, coat=0.03)
brand_ink = v4.mat("burnt_umber_brand", (0.20,0.105,0.045), roughness=0.84)
endwood = v4.wood("beech_endgrain", light=(0.59, 0.40, 0.23), dark=(0.45, 0.28, 0.15), grain_scale=11, roughness=0.72, coat=0.03)
brass = v4.metal("satin_brass", color=(0.72, 0.51, 0.24), roughness=0.42)
hinge_brass = v4.metal("hinge_brass", color=(0.86,0.65,0.31), roughness=0.34)
steel = v4.metal("brushed_steel", color=(0.58, 0.60, 0.60), roughness=0.42)
rubber = v4.rubber("charcoal_rubber", (0.10, 0.105, 0.10))
crumbwood = v4.wood("maple_crumb_tray", light=(0.82, 0.68, 0.48), dark=(0.70, 0.54, 0.34), grain_scale=10, roughness=0.68, coat=0.03)
slotdark = v4.mat("vent_recess_shadow", (0.12, 0.075, 0.04), roughness=0.88)
steel = v4.metal("satin_steel", color=(0.62, 0.64, 0.64), roughness=0.45)

# Dimensions in metres. World: X left/right, Y front(-) to back(+), Z up.
W, D = 0.44, 0.32
T = 0.014
base_z = 0.046
body_h = 0.174
body_top = base_z + body_h         # 0.220
inner_w = W - 2*T
inner_d = D - 2*T

carcass = v4.body("carcass")
lid = v4.body("lid")

# Slightly irregular grain gives each board a natural hand-finished figure.
for wm in (wood, frontwood, lidwood, endwood, crumbwood):
    noise = next((n for n in wm.node_tree.nodes if n.type == "TEX_NOISE"), None)
    if noise:
        noise.inputs["Scale"].default_value = 2.2
        noise.inputs["Distortion"].default_value = 2.4
        noise.inputs["Detail"].default_value = 10.0
    wave = next((n for n in wm.node_tree.nodes if n.type == "TEX_WAVE"), None)
    if wave:
        wave.inputs["Distortion"].default_value = 5.0

# Fixed open-top carcass: edges meet, with a dark floor liner directly on the base.
v4.box("base_plate", (W, D, T), (0, 0, base_z + T/2), bevel=0.003, material=wood, body=carcass)
wall_h = body_h - T
wall_z = base_z + T + wall_h/2
side_left = v4.box("side_left", (T, D, wall_h), (-W/2+T/2, 0, wall_z), bevel=0.003, material=wood, body=carcass)
side_right = v4.box("side_right", (T, D, wall_h), (W/2-T/2, 0, wall_z), bevel=0.003, material=wood, body=carcass)
# Back wall terminates at the side walls; a heavier rail gives the lid hinge a believable mount.
rear_wall = v4.box("rear_wall", (inner_w, T, wall_h), (0, D/2-T/2, wall_z), bevel=0.002, material=endwood, body=carcass)
# A narrow continuous rebate exposes the cylindrical hinge barrel along the rear top edge.
rebate = v4.box("rear_hinge_rebate",(inner_w+0.004,0.024,0.024),(0,D/2-T/2,body_top),bevel=0.002)
v4.boolean(rear_wall,rebate)
# The single access is from above: a solid front board replaces the extra door.
front_wall = v4.box("front_wall", (inner_w, T, wall_h), (0, -D/2+T/2, wall_z), bevel=0.003, material=frontwood, body=carcass)
# End-grain rim caps make the real panel thickness legible around the open mouth.
for sx in (-1, 1):
    v4.box(f"side_rim_cap_{sx}", (T, D-0.010, 0.003), (sx*(W/2-T/2), 0, body_top-0.0015), bevel=0.001, material=endwood, body=carcass)
v4.box("rear_rim_cap", (inner_w-0.004, T, 0.003), (0, D/2-T/2, body_top-0.0015), bevel=0.0008, material=endwood, body=carcass)
# A removable-looking maple crumb tray / cutting board rests directly on the wood floor.
tray_w, tray_d = inner_w-0.024, inner_d-0.030
tray_z = base_z + T + 0.0025
tray = v4.box("maple_crumb_tray", (tray_w, tray_d, 0.005), (0, 0, tray_z), bevel=0.002, material=crumbwood, body=carcass)
# Thin darker end-grain edging distinguishes the removable board from the carcass floor.
for sy in (-1,1):
    v4.box(f"tray_endgrain_{sy}",(tray_w-0.016,0.004,0.001),(0,sy*(tray_d/2-0.006),tray_z+0.003),bevel=0.0005,material=endwood,body=carcass)
for sx in (-1,1):
    v4.box(f"tray_sidegrain_{sx}",(0.004,tray_d-0.016,0.001),(sx*(tray_w/2-0.006),0,tray_z+0.003),bevel=0.0005,material=endwood,body=carcass)
# A shallow finger scallop is represented by a small brass inset pull at the front edge.
v4.box("tray_pull_recess", (0.040,0.001,0.008), (0,-tray_d/2-0.0005,tray_z), bevel=0.003, material=brass, body=carcass)

# Four low, subtly tapered feet; rubber pads touch the counter at z=0.
for i, (sx, sy) in enumerate(((-1,-1),(1,-1),(-1,1),(1,1))):
    x, y = sx*(W/2-0.045), sy*(D/2-0.045)
    v4.cylinder(f"foot_mount_{i}", 0.014, 0.008, (x,y,base_z-0.004), material=brass, body=carcass, bevel=0.001)
    v4.lathe(f"wood_foot_{i}", [(0,0.002),(0.012,0.002),(0.015,0.006),(0.014,0.018),(0.012,0.034),(0.010,0.039),(0,0.039)],
             loc=(x,y,0), material=endwood, body=carcass)
    v4.cylinder(f"rubber_pad_{i}", 0.012, 0.004, (x,y,0.002), material=rubber, body=carcass)

# Fixed hinge rail across the rear, with a brass continuous pin line and mounting caps.
rail_z = body_top - 0.0015
v4.box("hinge_rail", (W-0.025, 0.016, 0.003), (0, D/2-0.022, rail_z), bevel=0.0008, material=brass, body=carcass)
hinge_y = D/2 - 0.015
hinge_z = body_top
v4.rod("lid_hinge_pin", (-W/2+0.020, hinge_y, hinge_z), (W/2-0.020, hinge_y, hinge_z), 0.0032, material=brass, body=carcass)
for sx in (-1,1):
    v4.cylinder(f"pin_cap_{sx}", 0.005, 0.004, (sx*(W/2-0.020),hinge_y,hinge_z), rot=(0,math.pi/2,0), material=brass, body=carcass)
# Three exterior hinge leaves and short offset bridges expose the rear mounting hardware.
for i,x in enumerate((-0.170,0.0,0.170)):
    v4.box(f"rear_hinge_leaf_{i}",(0.020,0.0018,0.021),(x,D/2+0.0009,body_top-0.011),bevel=0.001,material=brass,body=carcass)
    v4.rod(f"rear_hinge_bridge_{i}",(x,D/2+0.001,body_top-0.001),(x,hinge_y,hinge_z),0.0016,material=brass,body=carcass)
    for dz in (-0.006,0.006):
        v4.cylinder(f"rear_hinge_screw_{i}_{dz}",0.0018,0.001,(x,D/2+0.002,body_top-0.011+dz),rot=(math.pi/2,0,0),segments=20,material=steel,body=carcass)
# Countersunk screws make the fixed piano-hinge leaf read as mounted hardware.
for x in (-0.16,-0.08,0,0.08,0.16):
    v4.cylinder(f"rail_screw_{x}", 0.0022, 0.0012, (x,D/2-0.030,body_top-0.003), rot=(0,0,0), segments=24, material=steel, body=carcass)

# Recessed rounded ventilation slots pass through both side walls; dark inner backs add depth.
for sx, side in ((-1,side_left),(1,side_right)):
    for k, y in enumerate((-0.078,-0.032,0.014,0.060)):
        cutter = v4.box(f"vent_cutter_{sx}_{k}", (T+0.004,0.024,0.0055), (sx*(W/2-T/2),y,0.151), bevel=0.0025)
        v4.boolean(side,cutter)
        inner_x = sx*(W/2-T)
        v4.box(f"vent_shadow_{sx}_{k}", (0.0008,0.019,0.0035), (inner_x+sx*0.0004,y,0.151), bevel=0.0015, material=slotdark, body=carcass)

# Lid: top panel sits on side rims; a shallow underside locating lip moves with it.
lid_depth = D + 0.012
lid_y = -0.006
lid_t = 0.016
v4.box("lid_panel", (W+0.012,lid_depth,lid_t), (0,lid_y,body_top+lid_t/2), bevel=0.005, material=lidwood, body=lid)
# End-grain veneer bands on the panel edges are attached flush to the lid.
for sx in (-1,1):
    v4.box(f"lid_endgrain_side_{sx}",(0.0015,lid_depth-0.014,lid_t-0.006),(sx*(W+0.012)/2+sx*0.00075,lid_y,body_top+lid_t/2),bevel=0.0005,material=endwood,body=lid)
for sy in (-1,1):
    v4.box(f"lid_endgrain_end_{sy}",(W+0.012-0.014,0.0015,lid_t-0.006),(0,lid_y+sy*(lid_depth/2+0.00075),body_top+lid_t/2),bevel=0.0005,material=endwood,body=lid)
# Underside lip is placed inside the opening, touching the panel and just clearing the walls.
lip_t, lip_h = 0.007, 0.010
lip_z = body_top - lip_h/2 + 0.0005
v4.box("lid_lip_left", (lip_t,0.215,lip_h), (-inner_w/2+0.004,0.005,lip_z), bevel=0.001, material=endwood, body=lid)
v4.box("lid_lip_right", (lip_t,0.215,lip_h), (inner_w/2-0.004,0.005,lip_z), bevel=0.001, material=endwood, body=lid)
v4.box("lid_lip_front", (inner_w-0.018,lip_t,lip_h), (0,-inner_d/2+0.004,lip_z), bevel=0.001, material=endwood, body=lid)
# Continuous brass hinge barrel sits in the rear rebate and connects visually to both leaves.
v4.cylinder("lid_hinge_barrel",0.0110,W-0.040,(0,hinge_y,hinge_z),rot=(0,math.pi/2,0),material=hinge_brass,body=lid)
# Matching moving hinge leaf sits flush on the lid underside and meets the fixed rail.
v4.box("lid_hinge_leaf", (W-0.045,0.012,0.0015), (0,hinge_y-0.012,body_top+0.00075), bevel=0.0005, material=brass, body=lid)
for x in (-0.16,-0.08,0,0.08,0.16):
    v4.cylinder(f"lid_leaf_screw_{x}",0.0018,0.001, (x,hinge_y-0.014,body_top+0.0004), segments=20, material=steel, body=lid)
# Magnetic catch at the front rim: the lid strike meets the fixed magnet when closed.
v4.box("lid_magnet_housing", (0.030,0.004,0.007), (0,-D/2+T+0.002,body_top-0.0035), bevel=0.0015, material=brass, body=carcass)
v4.box("lid_strike_plate", (0.026,0.010,0.001), (0,-D/2+T+0.002,body_top-0.0005), bevel=0.0005, material=steel, body=lid)
# Oversized fitted lift pull with metal mounting plates, proud standoffs, and four screws.
handle_top = body_top + lid_t
for x in (-0.076,0.076):
    v4.box(f"grip_mount_plate_{x}",(0.028,0.026,0.002),(x,-0.082,handle_top+0.001),bevel=0.002,material=endwood,body=lid)
    v4.cylinder(f"grip_standoff_{x}",0.008,0.015,(x,-0.082,handle_top+0.0095),material=brass,body=lid)
    for sy in (-1,1):
        v4.cylinder(f"grip_mount_screw_{x}_{sy}",0.0024,0.0012,(x,-0.082+sy*0.009,handle_top+0.0026),segments=20,material=steel,body=lid)
v4.rod("lid_lift_grip",(-0.076,-0.082,handle_top+0.0245),(0.076,-0.082,handle_top+0.0245),0.007,material=endwood,body=lid)
v4.joint("lid_hinge", "revolute", carcass, lid, origin=(0,hinge_y,hinge_z), axis=(1,0,0), limits=(-math.radians(110),0))

# The front is a plain fixed fascia; dark low-relief lettering reads as a maker's brand, not a door seam.
front_face_y = -D/2
v4.text("maker_mark", "BREAD", 0.027, loc=(0,front_face_y-0.002,wall_z+0.012), rot=(math.pi/2,0,0),
        material=brand_ink, body=carcass, extrude_depth=0.0003, on=front_wall, height=0.0004)
# Refine the library wood node mapping: less extreme anisotropy breaks up repeated streaks.
for wm in bpy.data.materials:
    if not wm.get("v4_wood") or not wm.use_nodes:
        continue
    for mapping in (n for n in wm.node_tree.nodes if n.type == "MAPPING"):
        targets = [ln.to_node.type for ln in mapping.outputs["Vector"].links]
        if "TEX_NOISE" in targets:
            mapping.inputs["Scale"].default_value = (3.0,18.0,18.0)
        elif "TEX_WAVE" in targets:
            mapping.inputs["Scale"].default_value = (1.0,7.2,7.2)
    for mix in (n for n in wm.node_tree.nodes if n.type == "MIX"):
        if mix.data_type == "FLOAT":
            mix.inputs["Factor"].default_value = 0.04

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