"""Horse: Chamfer at growing prefixes of one encode, for one package checkout. Appends to horse_ladder.csv.
    env -u PYTHONPATH ~/code/fcp_devel/.venv/bin/python run.py API LABEL"""
import csv
import sys
import time
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_object  # noqa: E402

import fcp  # noqa: E402

sys.modules["fcp.encode"].MAX_ATOMS = 1 << 24
OBJ, LAYERS, N, M = "Breyer_Horse_Of_The_Year_2015", 256, 64, 24
m = load_object(OBJ)
ev = Evaluator(m)
d = fcp.encode(m, atoms=1 << 24, layers=LAYERS, N=N, M=M, up=UP, device="cuda", parts="tracked-fit")
full = len(d.atoms[0])
ladder = sorted({b for k in range(3, 15) for b in (1 << k, 3 << (k - 1))} | {full})
ladder = [b for b in ladder if b <= full]
out = Path(__file__).with_name("horse_ladder.csv")
new = not out.exists()
with out.open("a", newline="") as f:
    w = csv.writer(f)
    if new:
        w.writerow(["version", "atoms", "full", "parts", "nbytes", "chamfer_pct", "p95_pct"])
    for T in ladder:
        dec = fcp.decode(d, atoms=T, device="cuda", resolution=128)
        s = ev(dec) if dec is not None and len(dec.faces) else None
        row = [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}"]
        w.writerow(row)
        print(row, flush=True)
