#!/usr/bin/env python3
import argparse
import sys
from stl import mesh
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
from PIL import Image
import io

parser = argparse.ArgumentParser(description='Convert STL to WebP via rendered preview')
parser.add_argument('input', help='Input STL file')
parser.add_argument('output', help='Output WebP file')
parser.add_argument('--angle', type=float, default=45, help='Azimuth angle')
parser.add_argument('--elev', type=float, default=30, help='Elevation angle')
parser.add_argument('--dpi', type=float, default=300, help='DPI')
args = parser.parse_args()

# Load STL
your_mesh = mesh.Mesh.from_file(args.input)

# Render
fig = plt.figure(dpi=args.dpi)
ax = fig.add_subplot(111, projection='3d')
ax.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))
ax.set_xlim(your_mesh.x.min(), your_mesh.x.max())
ax.set_ylim(your_mesh.y.min(), your_mesh.y.max())
ax.set_zlim(your_mesh.z.min(), your_mesh.z.max())
ax.view_init(elev=args.elev, azim=args.angle)
plt.tight_layout()

# Save to PNG buffer
buf = io.BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', dpi=args.dpi)
buf.seek(0)
plt.close()

# Convert to WebP
img = Image.open(buf)
img.save(args.output, 'webp', quality=95)
print(f"Rendered {args.input} -> {args.output}")
