#!/usr/bin/env python3
"""
Window 20x60mm - versão com anatomia CORRETA.

Z=0-1.6:  Perímetro retangular + furo oblongo central
Z=1.6-3.2: Apenas lado DIREITO (XP) sobe
Z=3.2-4.8: Apenas lado ESQUERDO (XN) sobe, com recorte retangular no topo
"""
from build123d import *
import os

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

W = 33.9
H = 13.9
T = 4.8

Z1 = 1.6
Z2 = 3.2
Z3 = 4.8

# Furo oblongo central (obround)
HOLE_W = 22.0   # comprimento X
HOLE_R = 4.5    # semicírculos das extremidades (Y/2)

# Faixa direita (Z1-Z2)
RW = 6.0   # largura X

# Faixa esquerda (Z2-Z3)
LW = 6.0

# Recorte retangular no topo (lado esquerdo)
CUT_W = 10.0
CUT_H = 4.0

# ========= CONSTRUIR =========

# 1. BASE com furo (Z=0 a Z=1.6)
outer = Rectangle(W, H)
outer = fillet(outer.vertices(), 0.5)

# Obround center hole
obr = Rectangle(HOLE_W, HOLE_R*2)
obr = fillet(obr.vertices(), HOLE_R)

base_shape = outer - obr
base = extrude(base_shape, Z1)

# 2. ASA DIREITA (Z=1.6 a Z=3.2)
right_pad = Rectangle(RW, H - 2.0)
right_pad = fillet(right_pad.vertices(), 0.3)
right = extrude(right_pad, Z2 - Z1)
right = Pos(W/2 - RW/2, 0, Z1) * right

# 3. ASA ESQUERDA (Z=3.2 a Z=4.8) - com recorte retangular
left_pad = Rectangle(LW, H - 2.0)
left_pad = fillet(left_pad.vertices(), 0.3)
left_solid = extrude(left_pad, Z3 - Z2)

# Recorte retangular no topo da asa esquerda
cut_rect = Rectangle(CUT_W, CUT_H)
cut_rect = fillet(cut_rect.vertices(), 0.5)
cut = extrude(cut_rect, Z3 - Z2)
# Position at center-left of the left pad
cut = Pos(-W/2 + LW/2, 0, 0) * cut

left = left_solid - cut
left = Pos(-W/2 + LW/2, 0, Z2) * left

# 4. CORPO FINAL
body = base
body += right
body += left

# 5. FILE TES
for z_h in [Z1, Z2]:
    try:
        e = body.edges().filter_by_position(Axis.Z, z_h-0.08, z_h+0.08)
        if len(e) > 0:
            body = fillet(e, 0.15)
    except:
        pass

# 6. EXPORTAR
stp = os.path.join(OUT, "window_anatomy.stp")
stl = os.path.join(OUT, "window_anatomy.stl")
export_step(body, stp)
export_stl(body, stl)
sz = body.bounding_box().size
print("OK: %.1f x %.1f x %.1f" % (sz.X, sz.Y, sz.Z))
print("  Base+obround: Z=0-1.6")
print("  Asa direita:   Z=1.6-3.2")
print("  Asa esquerda:  Z=3.2-4.8 (com recorte)")
