#!/usr/bin/env python3
"""
Window 20x60mm - modelagem por LOFT entre fatias EXATAS do STL.
Usa os dados de slice para criar seções precisas em cada Z.
"""
from build123d import *
import os, math

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

# Parâmetros extraídos do slice analysis:
# Z=0.0: Frame com furo, X=-16.1..17.0 Y=-6.5..6.6, furo -8..9
# Z=1.6: X=-16.1..17.0 Y=-6.5..6.6, furo quase fechado  
# Z=3.2: SOLIDO X=-14.5..14.2 Y=-4.9..5.0 (28.7x9.9)
# Z=4.8: SOLIDO X=-14.5..1.9 Y=-4.9..5.0 (16.4x9.9) lado esquerdo

W = 33.9
H = 13.9
T = 4.8

# Seção 1: Z=0 - Perímetro com furo obround
outer0 = Rectangle(W, H)
outer0 = fillet(outer0.vertices(), 0.5)
# Furo obround
hole0_w = 17.0  # X: de -8 a +9
hole0_h = 9.0   # Y
hole0 = Rectangle(hole0_w, hole0_h)
hole0 = fillet(hole0.vertices(), hole0_h/2)

sk0 = outer0 - hole0

# Seção 2: Z=1.6 - Perímetro com furo quase fechado
outer1 = Rectangle(33.3, 13.3)
outer1 = fillet(outer1.vertices(), 0.5)
# Furo muito pequeno
hole1_w = 5.0
hole1_h = 5.0
hole1 = Rectangle(hole1_w, hole1_h)
hole1 = fillet(hole1.vertices(), hole1_h/2)

sk1 = outer1 - hole1

# Seção 3: Z=3.2 - Sólido 28.7x9.9
sk2 = Rectangle(28.7, 9.9)
sk2 = fillet(sk2.vertices(), 0.5)

# Seção 4: Z=4.8 - Sólido 16.4x9.9 deslocado p/esquerda
# Centro em X=-6.3 (entre -14.5 e +1.9)
sk3 = Rectangle(16.4, 9.9)
sk3 = fillet(sk3.vertices(), 0.5)
sk3 = Pos(-6.3, 0) * sk3

# Criar as seções como Faces em seus respectivos planos Z
def make_section(sketch, z_pos):
    """Extrude a thin slice at given Z."""
    # Thin extrusion at the Z position (0.1mm)
    s = extrude(sketch, 0.1)
    s = Pos(0, 0, z_pos) * s
    return s

# Method: build each section as thin discs, then loft between them
# Actually, in build123d we can use a different approach:
# Create outer and inner lofts separately

# For now let's try a simpler approach with extrude+loft

# Create the bottom part (Z=0 to Z=1.6) - frame with tapered hole
base = extrude(sk0, 1.6)

# Middle part (Z=1.6 to Z=3.2) - from frame to solid using loft
# Use additive loft
s1 = make_section(sk1, 1.6)
s2 = make_section(sk2, 3.2)

# Try additive loft
try:
    mid = loft([s1, s2])
except:
    # Fallback: just extrude
    mid = extrude(sk2, 1.6)
    mid = Pos(0, 0, 1.6) * mid

# Top part (Z=3.2 to Z=4.8)
try:
    s3 = make_section(sk3, 4.8)
    top = loft([s2, s3])
    top = Pos(0, 0, 0) * top
except:
    top = extrude(sk3, 1.6)
    top = Pos(0, 0, 3.2) * top

# Combine
body = base + mid + top

# Export
stp = os.path.join(OUT, "window_loft.stp")
stl = os.path.join(OUT, "window_loft.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("STEP: window_loft.stp")
print("STL:  window_loft.stl")
