#!/usr/bin/env python3
"""
Window 20x60mm - CORRIGIDA.
Z=0-3.2: Simétrico - perímetro com furo obround que afina até fechar
Z=3.2-4.8: Assimétrico - só lado ESQUERDO continua (com recorte decorativo)
"""
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

# Parâmetros das fatias
# Z=0: 33.1x13.1, furo 17mm (obround)
# Z=1.6: 33.1x13.1, furo ~5mm
# Z=3.2: 28.7x9.9, SEM furo
# Z=4.8: 16.4x9.9, lado esquerdo (-14.5 a +1.9)

HOLE_W0 = 17.0  # largura furo na base (Z=0)
HOLE_W16 = 5.0  # largura furo em Z=1.6
HOLE_H = 9.0    # altura furo

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

hole0 = Rectangle(HOLE_W0, HOLE_H)
hole0 = fillet(hole0.vertices(), HOLE_H/2)
sk_base = outer_base - hole0
base = extrude(sk_base, 1.6)

# 2. TRANSIÇÃO Z=1.6 a Z=3.2: frame afina + furo fecha
# Seção intermediária em Z=1.6 com furo pequeno
outer_mid = Rectangle(31.0, 11.5)  # tapered from 33.1 to 28.7
outer_mid = fillet(outer_mid.vertices(), 0.5)

hole1 = Rectangle(HOLE_W16, HOLE_H - 2)
hole1 = fillet(hole1.vertices(), (HOLE_H-2)/2)
sk_mid = outer_mid - hole1
# Na prática fazemos um loft entre as seções

# Criar seções em Z para loft
# Section at Z=1.6 (thin slice)
s_base = extrude(sk_base, 0.01)
s_base = Pos(0, 0, 1.6) * s_base

# Section at Z=3.2 (solid, tapered)  
sk_top_sym = Rectangle(28.7, 9.9)
sk_top_sym = fillet(sk_top_sym.vertices(), 0.5)
s_top_sym = extrude(sk_top_sym, 0.01)
s_top_sym = Pos(0, 0, 3.2) * s_top_sym

# Loft entre base e topo simétrico (Z=1.6 a Z=3.2)
try:
    mid = loft([s_base, s_top_sym])
except:
    # fallback: simple extrude with draft
    mid = extrude(sk_top_sym, 1.6)
    mid = Pos(0, 0, 1.6) * mid

# 3. TOPO (Z=3.2 a Z=4.8): só lado esquerdo
sk_top_l = Rectangle(16.4, 9.9)
sk_top_l = fillet(sk_top_l.vertices(), 0.5)
sk_top_l = Pos(-6.3, 0) * sk_top_l  # centered at X=-6.3

s_top_l = extrude(sk_top_l, 0.01)
s_top_l = Pos(0, 0, 4.8) * s_top_l

try:
    top = loft([s_top_sym, s_top_l])
except:
    top = extrude(sk_top_l, 1.6)
    top = Pos(0, 0, 3.2) * top

# 4. COMBINAR
body = base + mid + top

# 5. ARREDONDAR CANTOS VERTICAIS
try:
    vert_edges = body.edges().filter_by_position(Axis.Z, 0.5, 4.3)
    body = fillet(vert_edges, 0.3)
except:
    pass

# 6. EXPORTAR
stp = os.path.join(OUT, "window_correct.stp")
stl = os.path.join(OUT, "window_correct.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("  Z=0-1.6: Frame 33.1x13.1 com furo obround 17mm")
print("  Z=1.6-3.2: Transição para sólido 28.7x9.9mm")
print("  Z=3.2-4.8: Colar esquerdo 16.4x9.9mm")
print("STEP: window_correct.stp")
