import csv, json, math, os
H = os.path.dirname(os.path.abspath(__file__))
R = H
I = json.load(open(os.path.join(H, "contact-sheet-layout-inputs.json")))
S = I["canvas_scale"]["value"]; PT = I["paper_points"]; L = I["layout"]
LAB = I["label_reserve_px"]["filenames_on"]; LIM = I["session_file_limit"]["value"]
PPI = 72 * S
assert abs(PPI - 151.2) < 1e-9
MM = 25.4 / PPI
rows = []
for pid in I["presets"]["ids"]:
    paper, g = pid.split("-"); c, r = map(int, g.split("x"))
    W = round(PT[paper][0] * S); Hh = round(PT[paper][1] * S)
    cw = (W - L["margin"]*2 - L["gap"]*(c-1)) / c
    ch = (Hh - L["header"] - L["footer"] - L["margin"] - L["gap"]*(r-1)) / r
    ih = ch - LAB
    n = c * r
    rows.append(dict(preset=pid, paper="A4" if paper=="a4" else "US Letter", orientation="portrait",
        grid=f"{c} x {r}", photos_per_sheet=str(n), sheets_for_72=str(math.ceil(LIM/n)),
        cell_width_mm=f"{cw*MM:.1f}", image_height_mm=f"{ih*MM:.1f}", cell_width_in=f"{cw/PPI:.2f}", image_height_in=f"{ih/PPI:.2f}",
        cell_width_px=f"{cw:.1f}", image_height_px=f"{ih:.1f}",
        page_raster_px=f"{W} x {Hh}", raster_px_per_inch=f"{PPI:.1f}", source_commit=I["commit"]))
assert [x["photos_per_sheet"] for x in rows] == ["6","12","20","30","12","20"]
assert (round(PT["a4"][0]*S), round(PT["a4"][1]*S)) == (1250, 1768)
assert (round(PT["letter"][0]*S), round(PT["letter"][1]*S)) == (1285, 1663)
EXP=[("95.4","78.6","3.76","3.09"),("62.6","56.2","2.46","2.21"),("46.2","42.8","1.82","1.68"),("36.4","33.8","1.43","1.33"),("64.6","51.8","2.54","2.04"),("47.7","39.2","1.88","1.54")]
for x,e in zip(rows,EXP): assert (x["cell_width_mm"],x["image_height_mm"],x["cell_width_in"],x["image_height_in"])==e,(x,e)
out = os.path.join(R, "contact-sheet-layout-benchmark.csv")
with open(out, "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0]), lineterminator="\n"); w.writeheader(); w.writerows(rows)
json.dump(rows, open(os.path.join(R, "contact-sheet-layout-benchmark.json"), "w"), indent=1)
with open(os.path.join(H, "contact-sheet-layout-compute-output.txt"), "w") as f:
    f.write(f"px per inch = 72 x {S} = {PPI:.1f}\n")
    for x in rows: f.write(" | ".join(x.values()) + "\n")
print(open(os.path.join(H, "contact-sheet-layout-compute-output.txt")).read())
