#!/usr/bin/env python3
"""
Parametric reconstruction of Window 20x60mm (keystone/DC).
Exports as STEP (Inventor/parametric compatible).
"""
from build123d import *
import os

OUT = "/app/projects/esp32-box/exports"
os.makedirs(OUT, exist_ok=True)

# ========= PARAMETERS =========
W = 33.9    # X: comprimento total (mm)
H = 13.9    # Y: altura total (mm)
T = 4.8     # Z: espessura total (mm)

# Tier 1 (base): Z=0 a Z=1.6 — tamanho cheio
T1_Z = 1.6

# Tier 2 (meio): Z=1.6 a Z=3.2 — encolhe
T2_X_OFF = 3.0   # encolhe 3mm de cada lado em X
T2_Y_OFF = 3.0   # encolhe 3mm de cada lado em Y
T2_Z = 3.2

# Tier 3 (topo): Z=3.2 a Z=4.8 — encolhe mais, deslocado
T3_W = 15.0
T3_H = 10.0
T3_SHIFT_X = -2.4  # deslocado para esquerda
T3_Z = 4.8

# Cutouts
KC_W = 17.0   # keystone cutout width
KC_H = 9.0    # keystone cutout height
KC_X = -3.0   # keystone center X position
DC_D = 8.0    # DC jack diameter
DC_X = 8.5    # DC jack center X

# ========= BUILD =========
mid = W / 2

# Tier 1: base full size
base = extrude(Rectangle(W, H), T1_Z)

# Tier 2: inner rectangle
t2_w = W - 2*T2_X_OFF
t2_h = H - 2*T2_Y_OFF
inner = extrude(Rectangle(t2_w, t2_h), T2_Z - T1_Z)
inner = Pos(0, 0, T1_Z) * inner

# Tier 3: top shifted rectangle
t3 = Pos(T3_SHIFT_X, 0) * Rectangle(T3_W, T3_H)
top = extrude(t3, T3_Z - T2_Z)
top = Pos(0, 0, T2_Z) * top

# Combine body
body = base + inner + top

# Chamfer/fillet between tiers for smooth transition
# Apply fillet on edges between base and inner tier
base_edges = body.edges().filter_by(GeomType.LINE).sort_by(Axis.Z)[:8]
# This needs refinement

# Keystone cutout (through inner + top tiers)
kc = Pos(KC_X, 0) * Rectangle(KC_W, KC_H)
kc_ext = extrude(kc, T)

# DC jack cutout
dc = Pos(DC_X, 0) * Circle(DC_D/2)
dc_ext = extrude(dc, T)

# Apply cuts
body -= kc_ext
body -= dc_ext

# Fillet the sharp edges between tiers for "curves"
# Select edges at Z=1.6 and Z=3.2 heights
try:
    edges_at_z = body.edges().filter_by_position(Axis.Z, T1_Z-0.1, T1_Z+0.1)
    body = fillet(edges_at_z, 0.5)
except:
    pass

# Export as STEP
step_path = os.path.join(OUT, "window_keystone_dc.stp")
export_step(body, step_path)
print("Exported: %s" % step_path)

# Also export STL for 3D printing
stl_path = os.path.join(OUT, "window_keystone_dc.stl")
export_stl(body, stl_path)
print("Exported: %s" % stl_path)

# Verify
from build123d import *
print("Dimensions: %.1f x %.1f x %.1f" % (body.bounding_box().size.X, body.bounding_box().size.Y, body.bounding_box().size.Z))
