import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from stl import mesh
from mpl_toolkits import mplot3d

def generate_stl_preview(stl_path: str, output_path: str):
    """
    Generates a PNG preview image for an STL file.
    Optimized for large files using decimation and smaller figure size.
    """
    try:
        # Load the STL file
        your_mesh = mesh.Mesh.from_file(stl_path)

        # Decimate if too many triangles to avoid OOM and slow rendering
        # 20,000 triangles is plenty for a small thumbnail
        vectors = your_mesh.vectors
        if len(vectors) > 20000:
            step = len(vectors) // 20000
            vectors = vectors[::step]

        # Create a new plot with smaller size for faster rendering
        figure = plt.figure(figsize=(4, 4))
        # Use transparent background
        figure.patch.set_alpha(0.0)
        
        axes = figure.add_subplot(111, projection='3d')
        axes.set_facecolor((0,0,0,0)) 

        # Add the mesh to the plot
        poly = mplot3d.art3d.Poly3DCollection(vectors)
        # Professional-looking blue/gray color
        poly.set_facecolor([0.2, 0.5, 0.8, 0.9])
        poly.set_edgecolor([0.1, 0.1, 0.1, 0.1]) # Reduced edge opacity
        axes.add_collection3d(poly)

        # Auto-scale the plot using original mesh bounds for accuracy
        scale = your_mesh.points.flatten()
        axes.auto_scale_xyz(scale, scale, scale)
        
        # Hide axes
        axes.set_axis_off()
        
        # Adjust view
        axes.view_init(elev=30, azim=45)

        # Save with lower DPI for speed
        plt.savefig(output_path, dpi=80, bbox_inches='tight', transparent=True)
        plt.close(figure)
        return True
    except Exception as e:
        print(f"Error generating preview: {e}")
        return False
