import numpy as np
from stl import mesh

def simplify_stl_grid(input_path, output_path, target_ratio=0.1):
    m = mesh.Mesh.from_file(input_path)
    vertices = m.vectors.reshape(-1, 3)
    
    min_v = vertices.min(axis=0)
    max_v = vertices.max(axis=0)
    bbox_size = max_v - min_v
    max_dim = np.max(bbox_size)
    
    # Adjust resolution to rough target_ratio by guessing. 
    # The number of vertices drops roughly by (resolution_factor)^2.
    # So if we want 10% faces, resolution_factor can be heuristically set.
    # Let's try 0.05
    grid_size = max_dim * 0.05
    
    v_idx = np.round((vertices - min_v) / grid_size).astype(np.int32)
    _, unique_idx, inv_idx = np.unique(v_idx, axis=0, return_index=True, return_inverse=True)
    
    new_vertices = vertices[unique_idx]
    faces = inv_idx.reshape(-1, 3)
    
    valid = (faces[:,0] != faces[:,1]) & (faces[:,1] != faces[:,2]) & (faces[:,0] != faces[:,2])
    valid_faces = faces[valid]
    
    new_m = mesh.Mesh(np.zeros(valid_faces.shape[0], dtype=mesh.Mesh.dtype))
    for i, f in enumerate(valid_faces):
        for j in range(3):
            new_m.vectors[i][j] = new_vertices[f[j]]
    
    new_m.update_normals()
    new_m.save(output_path)

