"""Chamfer and p95 at growing prefixes of one encode, per object, for one package checkout; appends to ladder.csv and
skips the objects already there, so it resumes.
    env -u PYTHONPATH ~/code/fcp_devel/.venv/bin/python run_all.py API LABEL"""
import csv
import sys
import traceback
from pathlib import Path

api, label = sys.argv[1], sys.argv[2]
sys.path.insert(0, api)
sys.path.insert(0, api + "/bench")
from common import UP, Evaluator, load_file  # noqa: E402

import fcp  # noqa: E402

sys.modules["fcp.encode"].MAX_ATOMS = 1 << 24
M_ = Path.home() / "code/data/meshes"
G = M_ / "data/meshes_clean"
C = M_ / "fcp_2910_collision/meshes"
OBJECTS = {"mug": G / "gso__Room_Essentials_Mug_White_Yellow.ply", "mug_ace": G / "gso__ACE_Coffee_Mug_Kristen_16_oz_cup.ply",
           "bowl": G / "gso__Threshold_Bead_Cereal_Bowl_White.ply",
           "bowl_serving": G / "gso__Threshold_Porcelain_Serving_Bowl_Coupe_White.ply",
           "bowl_dog": G / "gso__Top_Paw_Dog_Bowl_Blue_Paw_Bone_Ceramic_25_fl_oz_total.ply",
           "flower_pot": G / "gso__Central_Garden_Flower_Pot_Goo_425.ply",
           "shoe": G / "gso__Timberland_Mens_Classic_2Eye_Boat_Shoe.ply", "jogger": G / "gso__Reebok_CLASSIC_JOGGER.ply",
           "dino": G / "gso__Schleich_Therizinosaurus_ln9cruulPqc.ply", "horse": G / "gso__Breyer_Horse_Of_The_Year_2015.ply",
           "spring": C / "spring.ply", "knot": C / "knot.ply"}
LAYERS, N, M = 256, 64, 24
out = Path(__file__).with_name("ladder.csv")
done = set()
if out.exists():
    done = {(r["object"], r["version"]) for r in csv.DictReader(out.open())}
with out.open("a", newline="") as f:
    w = csv.writer(f)
    if not done:
        w.writerow(["object", "version", "atoms", "full", "parts", "nbytes", "chamfer_pct", "p95_pct"])
    for name, path in OBJECTS.items():
        if (name, label) in done:
            continue
        try:
            m = load_file(path)
            ev = Evaluator(m)
            d = fcp.encode(m, atoms=1 << 24, layers=LAYERS, N=N, M=M, up=UP if path.parent == G else None, device="cuda", parts="tracked-fit")
            full = len(d.atoms[0])
            ladder = sorted({b for k in range(3, 16) for b in (1 << k, 3 << (k - 1))} | {full})
            for T in [b for b in ladder if b <= full]:
                dec = fcp.decode(d, atoms=T, device="cuda", resolution=128)
                s = ev(dec) if dec is not None and len(dec.faces) else None
                w.writerow([name, label, T, full, len(d.parts), d.prefix(T).nbytes, "" if s is None else f"{s['chamfer_pct']:.5f}",
                            "" if s is None else f"{s['p95_pct']:.4f}"])
            f.flush()
            print("done", name, label, full, "atoms", len(d.parts), "parts", flush=True)
        except Exception:
            print("FAILED", name, label, flush=True)
            traceback.print_exc()
