#!/usr/bin/env python3
"""Render STL as ASCII art views."""
import struct, numpy as np

path = "/app/projects/esp32-box/original/Window 20x60mm.stl"

with open(path, "rb") as f:
    f.read(80)
    n = struct.unpack("<I", f.read(4))[0]
    all_verts = []
    for i in range(n):
        f.read(12)
        for j in range(3):
            x,y,z = struct.unpack("<fff", f.read(12))
            all_verts.append([x,y,z])
        f.read(2)

pts = np.array(all_verts)
cx, cy = pts[:,0].mean(), pts[:,1].mean()
pts[:,0] -= cx
pts[:,1] -= cy

W = 33.9; H = 13.9

def ascii_view(pts_2d, x_min, x_max, y_min, y_max, width=50, height=25):
    x_bins = np.linspace(x_min, x_max, width+1)
    y_bins = np.linspace(y_min, y_max, height+1)
    grid = np.zeros((height, width), dtype=int)
    for x, y in pts_2d:
        xi = int(np.clip(np.searchsorted(x_bins, x)-1, 0, width-1))
        yi = int(np.clip(np.searchsorted(y_bins, y)-1, 0, height-1))
        grid[yi, xi] = min(grid[yi, xi]+1, 9)
    return grid

# TOP VIEW at Z=0 (base outline)
print("=== TOP VIEW (Z=0 base) ===")
mask = (np.round(pts[:,2],1) == 0.0)
grid = ascii_view(pts[mask][:,[0,1]], -W/2-2, W/2+2, -H/2-2, H/2+2)
density = pts[mask][:,[0,1]]
for row in grid:
    print("  " + "".join("X" if c>0 else "." for c in row))

print("\n=== TOP VIEW (Z=1.6) ===")
mask = (np.round(pts[:,2],1) == 1.6)
grid = ascii_view(pts[mask][:,[0,1]], -W/2-2, W/2+2, -H/2-2, H/2+2)
for row in grid:
    print("  " + "".join("X" if c>0 else "." for c in row))

print("\n=== TOP VIEW (Z=3.2) ===")
mask = (np.round(pts[:,2],1) == 3.2)
grid = ascii_view(pts[mask][:,[0,1]], -W/2-2, W/2+2, -H/2-2, H/2+2)
for row in grid:
    print("  " + "".join("X" if c>0 else "." for c in row))

print("\n=== TOP VIEW (Z=4.8) ===")
mask = (np.round(pts[:,2],1) == 4.8)
grid = ascii_view(pts[mask][:,[0,1]], -W/2-2, W/2+2, -H/2-2, H/2+2)
for row in grid:
    print("  " + "".join("X" if c>0 else "." for c in row))
