"""Detailed countertop cordless telephone. Run with the supplied Blender executable."""
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()

# Consumer-electronics palette: charcoal blue-gray housing, graphite controls,
# satin nickel contacts and a muted green LCD.
shell = v4.plastic("warm_charcoal_housing", (0.105, 0.135, 0.155), roughness=0.34, texture=0.12)
shell_light = v4.plastic("upper_shell_gray", (0.22, 0.255, 0.27), roughness=0.34, texture=0.12)
panel = v4.plastic("keypad_panel", (0.055, 0.070, 0.079), roughness=0.39, texture=0.18)
rubber = v4.rubber("key_rubber", (0.025, 0.032, 0.036))
keycap = v4.plastic("soft_gray_keycaps", (0.34, 0.37, 0.37), roughness=0.32, texture=0.1)
talk_keymat = v4.plastic("talk_key_green", (0.20, 0.43, 0.31), roughness=0.34, texture=0.1)
end_keymat = v4.plastic("end_key_coral", (0.66, 0.25, 0.20), roughness=0.34, texture=0.1)
black = v4.mat("speaker_grille_black", (0.012, 0.016, 0.018), roughness=0.72)
lcd_bezel = v4.plastic("lcd_bezel", (0.018, 0.027, 0.029), roughness=0.24, texture=0.08)
lcd_glass = v4.glass("lcd_glass", (0.50, 0.58, 0.48), roughness=0.17)
lcd_bg = v4.mat("lcd_backlight", (0.19, 0.29, 0.20), roughness=0.25)
lcd_ink = v4.mat("lcd_segments", (0.025, 0.07, 0.035), roughness=0.35)
white = v4.mat("legend_warm_white", (0.82, 0.84, 0.80), roughness=0.5)
nickel = v4.metal("satin_nickel", color=(0.72, 0.75, 0.74), roughness=0.31, brushed=True)
dark_metal = v4.metal("dark_satin_metal", color=(0.23, 0.28, 0.29), roughness=0.37, brushed=False)
gold = v4.metal("warm_gold_contacts", color=(0.83, 0.58, 0.20), roughness=0.24, brushed=True)
green_led = v4.emissive("charge_led_green", (0.15, 0.72, 0.34), strength=1.6)
amber_led = v4.emissive("status_led_amber", (1.0, 0.43, 0.08), strength=1.0)
footmat = v4.rubber("foot_grip", (0.025, 0.03, 0.032))

# Dimensions (m): 240 x 165 mm base, 224 x 56 mm handset.
base = v4.body("base")
handset = v4.body("handset")
key5 = v4.body("base_key_5")
antenna = v4.body("antenna")
clip = v4.body("belt_clip")

# --- Base enclosure: softly rounded lower case with a raised top deck ----------------
lower_case = v4.box("base_lower_case", (0.240, 0.165, 0.031), (0, 0, 0.016), bevel=0.010,
                    material=shell, body=base)
deck = v4.box("base_top_deck", (0.232, 0.161, 0.004), (0, -0.002, 0.0335), bevel=0.008,
              material=shell_light, body=base)
keypad = v4.box("front_keypad_inset", (0.146, 0.082, 0.0018), (0, -0.039, 0.0361), bevel=0.006,
                material=panel, body=base)
for target in (deck, keypad):
    cutter = v4.box("temporary_key_aperture", (0.034, 0.015, 0.012), (0, -0.048, 0.035), bevel=0)
    v4.boolean(target, cutter)
# Clearance well through the lower case lets the central plunger move down 4 mm.
v4.boolean(lower_case, v4.box("temporary_key_plunger_well", (0.034, 0.015, 0.035),
                              (0, -0.048, 0.021), bevel=0))
# Deep narrow cradle slot under the handset's recessed belt clip. The slot remains
# hidden while docked and gives the clip room to swing down through its full arc.
for target in (lower_case, deck):
    cutter = v4.box("temporary_clip_clearance", (0.081, 0.024, 0.040),
                     (-0.0125, 0.040, 0.021), bevel=0)
    v4.boolean(target, cutter)
# Recessed charger well. The dark inset floor is below the surrounding deck, while
# angled side cheeks and a heel stop capture the handset without blocking its lift.
for target in (lower_case, deck):
    v4.boolean(target, v4.box("temporary_cradle_well", (0.228, 0.078, 0.018),
                              (0, 0.040, 0.035), bevel=0))
v4.box("cradle_well_liner", (0.224, 0.074, 0.003), (0, 0.040, 0.0265), bevel=0.004,
       material=panel, body=base)
# Open a narrow passage through the liner under the clip so its raised spring tip
# can swing freely while the handset remains seated.
v4.boolean(bpy.data.objects["cradle_well_liner"],
          v4.box("temporary_clip_liner_slot", (0.081, 0.024, 0.050),
                 (-0.0125, 0.040, 0.0265), bevel=0))
# Side cheeks lean inward by 15 degrees and wrap the handset sides; the heel wall
# is a low, angled stop around the handset's lower end.
for s in (-1, 1):
    v4.box(f"cradle_side_cheek_{s}", (0.198, 0.007, 0.019), (0, 0.0065 if s < 0 else 0.0735, 0.0355),
           rot=(math.radians(15) * s, 0, 0), bevel=0.0025, material=shell_light, body=base)
v4.box("cradle_heel_stop", (0.006, 0.064, 0.014), (-0.117, 0.040, 0.040),
       rot=(0, math.radians(-12), 0), bevel=0.002, material=shell_light, body=base)
# Fine molded frame line around the inset, assembled as four touching edge rails.
for nm, sz, loc in (
    ("keypad_frame_top", (0.142, 0.0012, 0.001), (0, 0.002, 0.0371)),
    ("keypad_frame_bottom", (0.142, 0.0012, 0.001), (0, -0.080, 0.0371)),
    ("keypad_frame_left", (0.0012, 0.082, 0.001), (-0.073, -0.039, 0.0371)),
    ("keypad_frame_right", (0.0012, 0.082, 0.001), (0.073, -0.039, 0.0371)),
):
    v4.box(nm, sz, loc, bevel=0.0004, material=dark_metal, body=base)

# Shallow lift-out cradle. Four low landing pads locate the handset on the well floor.
for sx in (-1, 1):
    for sy in (-1, 1):
        x, y = sx * 0.078, 0.040 + sy * 0.018
        v4.box(f"cradle_landing_{sx}_{sy}", (0.018, 0.013, 0.0085), (x, y, 0.03225),
               bevel=0.003, material=panel, body=base)
# Two sprung gold charging pins at the heel end, visibly raised from the well.
for i, y in enumerate((0.028, 0.052)):
    v4.cylinder(f"charge_contact_well_{i}", 0.0045, 0.0070, (-0.100, y, 0.0315),
                segments=32, bevel=0.00035, material=dark_metal, body=base)
    v4.cylinder(f"charge_contact_{i}", 0.0027, 0.0050, (-0.100, y, 0.0341),
                segments=32, bevel=0.00045, material=gold, body=base)
# Speakerphone perforations in the vertical front wall.
for row in range(3):
    for col in range(7):
        x = -0.084 + col * 0.008
        z = 0.011 + row * 0.006
        v4.cylinder(f"speakerphone_port_{row}_{col}", 0.00125, 0.0010,
                    (x, -0.0826, z), rot=(math.pi / 2, 0, 0), segments=16, bevel=0.0002,
                    material=black, body=base)
# Charge/status indicators on the exposed right-front deck.
v4.cylinder("charge_indicator_lens", 0.0021, 0.0014, (0.085, -0.069, 0.0359),
            segments=24, bevel=0.0004, material=green_led, body=base)
v4.cylinder("in_use_indicator_lens", 0.0015, 0.0014, (0.085, -0.057, 0.0359),
            segments=24, bevel=0.0003, material=amber_led, body=base)

# Base keypad, 12 equal-bezel keys on a regular 3 x 4 matrix. Only 5 is movable.
key_x = (-0.047, 0.0, 0.047)
key_y = (-0.064, -0.048, -0.032, -0.016)
key_labels = (("1", "2", "3"), ("4", "5", "6"), ("7", "8", "9"), ("*", "0", "#"))
for ri, row in enumerate(key_labels):
    for ci, lab in enumerate(row):
        x, y = key_x[ci], key_y[ri]
        bezel = v4.box(f"base_key_{ri}_{ci}_bezel", (0.027, 0.014, 0.0012), (x, y, 0.0376),
                       bevel=0.0022, material=dark_metal, body=base)
        if lab == "5":
            v4.boolean(bezel, v4.box("temporary_key_bezel_opening", (0.022, 0.010, 0.004),
                                     (x, y, 0.0376), bevel=0))
            host = v4.box("base_key_5_cap", (0.020, 0.010, 0.0042), (x, y, 0.0392),
                          bevel=0.0020, material=keycap, body=key5)
            v4.box("base_key_5_plunger", (0.031, 0.012, 0.006), (x, y, 0.0341),
                   bevel=0.0005, material=dark_metal, body=key5)
            v4.text("base_key_5_legend", lab, 0.0060, (x, y, 0.0413), material=white,
                    body=key5, on=host, height=0.00025)
        else:
            host = v4.box(f"base_key_{ri}_{ci}_cap", (0.020, 0.010, 0.0042), (x, y, 0.0392),
                          bevel=0.0020, material=keycap, body=base)
            v4.text(f"base_key_{ri}_{ci}_legend", lab, 0.0060, (x, y, 0.0413), material=white,
                    body=base, on=host, height=0.00025)
# Function keys above the number pad and short molded legends.
for nm, x, lab in (("vol_down", -0.035, "VOL -"), ("page", 0.0, "PAGE"), ("vol_up", 0.035, "VOL +")):
    cap = v4.box(f"function_{nm}_key", (0.020, 0.006, 0.0035), (x, -0.004, 0.0388),
                 bevel=0.0018, material=rubber, body=base)
    v4.text(f"function_{nm}_label", lab, 0.0025, (x, -0.004, 0.04065), material=white,
            body=base, on=cap, height=0.00016)
# Four small non-slip feet, recessed into the bottom corners.
for sx in (-1, 1):
    for sy in (-1, 1):
        v4.cylinder(f"base_foot_{sx}_{sy}", 0.010, 0.003, (sx * 0.086, sy * 0.060, 0.0015),
                    segments=32, bevel=0.001, material=footmat, body=base)
# Compact DECT identity plate fills the open right-hand deck area.
brand_outer = v4.box("base_brand_bezel", (0.034, 0.026, 0.0014), (0.093, -0.025, 0.0359),
                      bevel=0.003, material=dark_metal, body=base)
brand_inner = v4.box("base_brand_plate", (0.030, 0.022, 0.0010), (0.093, -0.025, 0.0369),
                      bevel=0.002, material=panel, body=base)
v4.text("base_brand_mark", "NORDTEL", 0.0035, (0.093, -0.022, 0.03742), material=white,
        body=base, on=brand_inner, height=0.00015)
v4.text("base_radio_mark", "DECT 2.4", 0.0025, (0.093, -0.0295, 0.03742), material=white,
        body=base, on=brand_inner, height=0.00012)

# --- Handset: tapered impression from layered rounded shells and a perimeter seam --------
# The 224 mm body rests on the four cradle pads at z=36.5 mm.
handset_outline = [
    (-0.112, -0.018), (-0.106, -0.024), (-0.090, -0.027), (-0.070, -0.025),
    (-0.050, -0.023), (0.040, -0.023), (0.060, -0.022), (0.080, -0.020),
    (0.100, -0.017), (0.111, -0.012), (0.112, 0.000), (0.111, 0.012),
    (0.100, 0.017), (0.080, 0.020), (0.060, 0.022), (0.040, 0.023),
    (-0.050, 0.023), (-0.070, 0.025), (-0.090, 0.027), (-0.106, 0.024),
    (-0.112, 0.018),
]
handset_shell = v4.extrude("handset_lower_shell", handset_outline, 0.025,
                           loc=(0.0, 0.040, 0.0365), bevel=0.006,
                           material=shell, body=handset)
# Internal antenna channel exits through the +X end cap. It is hidden within the
# casing at rest and guides the inner whip rod throughout its 60 mm extension.
antenna_channel = v4.box("temporary_antenna_channel", (0.092, 0.006, 0.006),
                         (0.070, 0.040, 0.049), bevel=0)
v4.boolean(handset_shell, antenna_channel)
# Shallow underside pocket seats the clip flush against the handset back.
clip_recess = v4.box("temporary_clip_recess", (0.079, 0.022, 0.006),
                     (-0.0125, 0.040, 0.0375), bevel=0)
v4.boolean(handset_shell, clip_recess)
face_outline = [(x, y * 0.94) for x, y in handset_outline]
v4.extrude("handset_front_face", face_outline, 0.0030,
           loc=(0.0, 0.040, 0.0605), bevel=0.0008,
           material=shell_light, body=handset)
# Narrow dark seam across the lower shell edge.
for side, y in (("near", 0.0174), ("far", 0.0626)):
    v4.box(f"handset_seam_inlay_{side}", (0.108, 0.0007, 0.00065), (0, y, 0.049), bevel=0.00025,
           material=dark_metal, body=handset)

# Earpiece: oblong recessed bezel with a regular field of acoustic perforations.
v4.box("earpiece_bezel", (0.026, 0.034, 0.0012), (0.087, 0.040, 0.06395), bevel=0.006,
       material=lcd_bezel, body=handset)
for r in range(4):
    for c in range(5):
        x = 0.077 + c * 0.005
        y = 0.025 + r * 0.010
        v4.box(f"earpiece_slot_{r}_{c}", (0.0031, 0.00105, 0.00045), (x, y, 0.06465),
               bevel=0.00045, material=black, body=handset)

# LCD at the centre of the handset. Layered frame, green-gray screen and legible status readout.
v4.box("lcd_outer_gasket", (0.047, 0.039, 0.0015), (-0.047, 0.040, 0.0640), bevel=0.0055,
       material=panel, body=handset)
v4.box("lcd_inner_bezel", (0.039, 0.031, 0.0010), (-0.047, 0.040, 0.06515), bevel=0.004,
       material=lcd_bezel, body=handset)
lcd = v4.box("lcd_window", (0.033, 0.024, 0.0007), (-0.047, 0.040, 0.0660), bevel=0.0028,
             material=lcd_bg, body=handset)
v4.text("lcd_readout", "12:48", 0.010, (-0.047, 0.041, 0.06638), material=lcd_ink,
        body=handset, on=lcd, height=0.00018)
v4.text("lcd_status", "1   FULL", 0.0044, (-0.047, 0.0325, 0.06638), material=lcd_ink,
        body=handset, on=lcd, height=0.00012)

# Handset keypad: four rows run along the handset's long axis, with three columns
# across its width, all between the LCD and earpiece grille.
h_x = (0.008, 0.023, 0.038, 0.053)
h_y = (0.022, 0.040, 0.058)
h_labels = (("1", "2", "3"), ("4", "5", "6"), ("7", "8", "9"), ("*", "0", "#"))
for ri, row in enumerate(h_labels):
    for ci, lab in enumerate(row):
        x, y = h_x[ri], h_y[ci]
        cap = v4.box(f"handset_key_{ri}_{ci}_cap", (0.011, 0.014, 0.0018), (x, y, 0.06435),
                     bevel=0.0012, material=rubber if lab not in ("5", "0") else keycap, body=handset)
        v4.text(f"handset_key_{ri}_{ci}_legend", lab, 0.0042, (x, y, 0.0653), material=white,
                body=handset, on=cap, height=0.00013)
# Talk and end keys sit between the display and the first dial row.
for nm, y, lab, matl in (("talk", 0.024, "TALK", talk_keymat), ("end", 0.056, "END", end_keymat)):
    cap = v4.box(f"handset_{nm}_key", (0.012, 0.014, 0.0018), (-0.006, y, 0.06435),
                 bevel=0.0018, material=matl, body=handset)
    v4.text(f"handset_{nm}_legend", lab, 0.0028, (-0.006, y, 0.0653), material=white,
            body=handset, on=cap, height=0.00012)
v4.cylinder("navigation_ring", 0.0058, 0.0018, (-0.006, 0.040, 0.0643),
            segments=40, bevel=0.0006, material=panel, body=handset)
v4.cylinder("navigation_select", 0.0025, 0.0015, (-0.006, 0.040, 0.0657),
            segments=32, bevel=0.0005, material=keycap, body=handset)
# Mouthpiece grille and microphone port at the far, lower end.
v4.box("mouthpiece_grille_recess", (0.014, 0.030, 0.0010), (-0.096, 0.040, 0.0637), bevel=0.004,
       material=panel, body=handset)
for r in range(3):
    for c in range(4):
        x = -0.100 + r * 0.0045
        y = 0.025 + c * 0.010
        v4.box(f"mouthpiece_slot_{r}_{c}", (0.0011, 0.0040, 0.00045), (x, y, 0.06445),
               bevel=0.00035, material=black, body=handset)
v4.cylinder("microphone_port", 0.0015, 0.0008, (-0.095, 0.040, 0.0639),
            segments=24, bevel=0.0002, material=black, body=handset)

# Underside mating pads align directly over the base charging contacts.
for i, y in enumerate((0.028, 0.052)):
    v4.box(f"handset_charge_pad_{i}", (0.009, 0.008, 0.0006), (-0.100, y, 0.0362), bevel=0.001,
           material=gold, body=handset)

# --- Independent button and telescoping whip -------------------------------------------
v4.joint("handset_lift", "prismatic", base, handset, origin=(0, 0.040, 0.0365),
         axis=(0, 0, 1), limits=(0.0, 0.055))
v4.joint("base_key_press", "prismatic", base, key5, origin=(0, -0.048, 0.0435),
         axis=(0, 0, -1), limits=(0.0, 0.0035))

# Telescoping antenna socket and guide are fixed to the +X end cap. The long inner
# rod is hidden in its channel at rest, stays overlapped inside the sleeve at full
# extension, and emerges along the handset's long axis.
end_axis = (0, math.pi / 2, 0)
v4.cylinder("antenna_root_grommet", 0.0048, 0.006, (0.115, 0.040, 0.049),
            rot=end_axis, segments=32, bevel=0.0008, material=dark_metal, body=handset)
v4.cylinder("antenna_escutcheon_flange", 0.0058, 0.0022, (0.1122, 0.040, 0.049),
            rot=end_axis, segments=40, bevel=0.0005, material=nickel, body=handset)
v4.cylinder("antenna_collar", 0.0042, 0.004, (0.1165, 0.040, 0.049),
            rot=end_axis, segments=40, bevel=0.0006, material=panel, body=handset)
v4.cylinder("antenna_outer_sleeve", 0.0032, 0.020, (0.121, 0.040, 0.049),
            rot=end_axis, segments=32, bevel=0.0007, material=black, body=handset)
v4.rod("whip_inner_rod", (0.032, 0.040, 0.049), (0.112, 0.040, 0.049), 0.00090,
       material=dark_metal, body=antenna, bevel=0.00015)
v4.rod("whip_mid_telescope", (0.070, 0.040, 0.049), (0.112, 0.040, 0.049), 0.00105,
       material=nickel, body=antenna, bevel=0.0001)
v4.rod("whip_tip_telescope", (0.095, 0.040, 0.049), (0.112, 0.040, 0.049), 0.00070,
       material=dark_metal, body=antenna, bevel=0.00008)
for i, x in enumerate((0.070, 0.095)):
    v4.cylinder(f"whip_section_band_{i}", 0.00115, 0.0012, (x, 0.040, 0.049),
                rot=end_axis, segments=24, bevel=0.00015, material=gold, body=antenna)
v4.rod("whip_tip_taper", (0.100, 0.040, 0.049), (0.112, 0.040, 0.049), 0.00062,
       material=nickel, body=antenna, bevel=0.0001)
v4.sphere("whip_tip_ball", 0.00092, (0.112, 0.040, 0.049), segments=20,
          material=nickel, body=antenna)
v4.joint("whip_extend", "prismatic", handset, antenna, origin=(0.112, 0.040, 0.049),
         axis=(1, 0, 0), limits=(0.0, 0.060))

# --- Back belt clip: formed spring leaf, raised toe and transverse hinge ------------------
clip_pivot = (-0.050, 0.040, 0.0385)
v4.cylinder("clip_hinge_barrel", 0.0020, 0.056, clip_pivot,
            rot=(math.pi / 2, 0, 0), segments=32, bevel=0.00035, material=nickel, body=clip)
# Side profile lifts at the free end like a real spring clip; extrusion spans the handset width.
clip_profile = [
    (-0.053, 0.0365), (-0.047, 0.0348), (0.006, 0.0327), (0.016, 0.0329),
    (0.022, 0.0342), (0.026, 0.0380), (0.023, 0.0385), (0.019, 0.0350),
    (0.014, 0.0344), (-0.047, 0.0366), (-0.053, 0.0380),
]
v4.extrude("belt_clip_sprung_leaf", clip_profile, 0.018,
           loc=(0, 0.049, 0), rot=(math.pi / 2, 0, 0), bevel=0.00045,
           material=nickel, body=clip)
v4.box("belt_clip_tip_pad", (0.008, 0.018, 0.0012), (0.023, 0.040, 0.0377), bevel=0.0005,
       material=dark_metal, body=clip)
for sy in (-1, 1):
    v4.cylinder(f"clip_pivot_cap_{sy}", 0.0023, 0.0012, (-0.050, 0.040 + sy * 0.0275, 0.0385),
                rot=(math.pi / 2, 0, 0), segments=24, bevel=0.0003, material=nickel, body=clip)
v4.joint("clip_hinge", "revolute", handset, clip, origin=clip_pivot,
         axis=(0, 1, 0), limits=(0.0, math.radians(15)))

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

# Supplemental underside view: isolate the lifted handset to show the gold pads
# and the formed spring leaf unobstructed. This render is independent of check's views.
v4.pose({"handset_lift": 0.055, "clip_hinge": math.radians(15)})
for moving_or_fixed_body in (v4.get_body("base"), v4.get_body("base_key_5")):
    for obj in bpy.data.objects:
        if obj.parent == moving_or_fixed_body and obj.type in {"MESH", "CURVE", "FONT"}:
            obj.hide_render = True
v4.studio()
studio_floor = bpy.data.objects.get("studio_floor")
if studio_floor:
    studio_floor.hide_render = True
lo, hi = v4.bounds()
v4.render(os.path.join(os.getcwd(), "underside.png"), view=(0.0, -0.45, -1.0),
          res=900, samples=48, lo=lo, hi=hi)
