#!/usr/bin/env python3
"""
Pipeline-Verifikation für 3d-druck-kiwi.
Prüft, ob trimesh + manifold3d + numpy + shapely funktionieren.
Bei Erfolg: STL wird in /tmp geschrieben und sofort gelöscht.

Usage (nach venv-Aktivierung):
    python3 /DATA/.hermes/skills/3d-printing/3d-druck-kiwi/scripts/verify_pipeline.py
"""

import sys
import numpy as np
import trimesh
from trimesh.creation import box, cylinder
from trimesh.primitives import Sphere
import manifold3d as m3d
import os


def trimesh_to_manifold(mesh):
    verts = np.asarray(mesh.vertices, dtype=np.float32)
    faces = np.asarray(mesh.faces, dtype=np.uint32)
    return m3d.Manifold(m3d.Mesh(vert_properties=verts, tri_verts=faces))


def manifold_to_trimesh(manifold):
    m = manifold.to_mesh()
    return trimesh.Trimesh(vertices=m.vert_properties[:, :3], faces=m.tri_verts)


def main():
    print("🔧 3D-Druck Pipeline-Check")
    print("-" * 40)

    # 1. Primitives erstellen
    b = box(extents=[20, 20, 10])
    s = Sphere(radius=6, subdivisions=2)
    s.apply_translation([0, 0, 5])
    print(f"[1] Primitives OK — box {b.faces.shape[0]} faces, sphere {s.faces.shape[0]} faces")

    # 2. manifold3d Konvertierung (float32 / uint32)
    mb = trimesh_to_manifold(b)
    ms = trimesh_to_manifold(s)
    print(f"[2] manifold3d Konvertierung OK")

    # 3. Boolean Differenz
    result = manifold_to_trimesh(mb - ms)
    print(f"[3] Boolean Differenz OK — {result.faces.shape[0]} faces")

    # 4. Validierung
    assert result.is_watertight, "FEHLER: Nicht watertight!"
    assert result.volume > 0, "FEHLER: Negatives Volumen!"
    print(f"[4] Validierung OK — watertight, volume={result.volume/1000:.3f} cm³")

    # 5. STL-Export (temporär)
    tmp = "/tmp/verify_test.stl"
    result.export(tmp)
    assert os.path.exists(tmp), "FEHLER: STL nicht geschrieben!"
    size = os.path.getsize(tmp)
    os.remove(tmp)
    print(f"[5] STL-Export OK — {size} bytes geschrieben")

    # 6. shapely (optional)
    try:
        from shapely.geometry import Polygon
        poly = Polygon([(0, 0), (10, 0), (10, 5), (0, 5)])
        ext = trimesh.creation.extrude_polygon(poly, height=2.0)
        assert ext.volume > 0
        print(f"[6] shapely Extrusion OK")
    except ImportError:
        print(f"[6] shapely nicht installiert — OK (optional)")

    print("-" * 40)
    print("✅ Pipeline funktioniert! Skill '3d-druck-kiwi' einsatzbereit.")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except AssertionError as e:
        print(f"\n❌ Pipeline-FEHLER: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Unerwarteter Fehler: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
