"""Independent STL checks for the frozen PP-270 plate. Requires trimesh."""
import math
import sys
from pathlib import Path
import numpy as np
import trimesh

for name in sys.argv[1:]:
    length = 40 if '40' in Path(name).stem else 52
    mesh = trimesh.load(name, force='mesh')
    expected_bounds = np.array([[-length / 2, -12, 0], [length / 2, 12, 5]])
    expected_volume = length * 24 * 5 - 80 * math.pi
    error = abs(mesh.volume - expected_volume) / expected_volume
    section = mesh.section(plane_origin=[0, 0, 2.5], plane_normal=[0, 0, 1])
    loops = section.discrete if section is not None else []
    holes = []
    for loop in loops:
        low, high = loop.min(axis=0), loop.max(axis=0)
        if high[0] - low[0] < 5 and high[1] - low[1] < 5:
            holes.append(((low + high) / 2)[:2])
            assert abs(high[0] - low[0] - 4) < 0.05
            assert abs(high[1] - low[1] - 4) < 0.05
    expected_centers = [(sx * (length / 2 - 6), sy * 6) for sx in (-1, 1) for sy in (-1, 1)]
    assert mesh.is_watertight and mesh.is_winding_consistent and mesh.volume > 0
    assert np.allclose(mesh.bounds, expected_bounds, atol=0.05)
    assert len(loops) == 5 and len(holes) == 4
    assert all(any(np.allclose(center, expected, atol=0.05) for center in holes) for expected in expected_centers)
    assert error < 0.01
    print(f'{Path(name).name}: PASS; watertight; bounds={mesh.bounds.tolist()}; 4 holes; mesh volume={mesh.volume:.6f} mm3; analytic error={error * 100:.4f}%')
