"""The gap of the decoded mesh's hull (qhull) to the source mesh's hull, beside the descriptor hull's: how much of the
gap is the encoding and how much the hull method. 128 layers, 6144 atoms, M = 64; out/decoded_gap.csv."""
import sys
sys.argv = [sys.argv[0], "x"]
from hull import OBJECTS, OUT, gaps  # noqa: E402
import numpy as np, pandas as pd, trimesh, fcp  # noqa: E402
from scipy.spatial import ConvexHull  # noqa: E402
from fcp_hull import convex_hull  # noqa: E402
rows = []
for name, path in OBJECTS.items():
    m = trimesh.load(path, force="mesh")
    V0 = np.asarray(m.vertices, np.float64)
    diag = float(np.linalg.norm(m.bounds[1] - m.bounds[0]))
    H0 = ConvexHull(V0); true = trimesh.Trimesh(V0, H0.simplices); true.fix_normals()
    d = fcp.encode(m, atoms=6144, layers=128, device="cpu")
    Vd = fcp.decode(d, device="cpu").vertices
    Hd = ConvexHull(Vd); dec = trimesh.Trimesh(Vd, Hd.simplices); dec.fix_normals()
    V, T = convex_hull(d, 64, 128); h = trimesh.Trimesh(V, T, process=False)
    r = dict(obj=name)
    r["dec_max"], r["dec_mean"] = gaps(true, dec, diag)
    r["fcp_max"], r["fcp_mean"] = gaps(true, h, diag)
    r["fcp_to_dec_max"], r["fcp_to_dec_mean"] = gaps(dec, h, diag)
    r["dec_vol"], r["fcp_vol"] = Hd.volume / H0.volume, h.volume / H0.volume
    rows.append(r)
    print({k: (round(v, 3) if isinstance(v, float) else v) for k, v in r.items()}, flush=True)
pd.DataFrame(rows).to_csv(OUT / "decoded_gap.csv", index=False)
