"""Check Part 1's figures and cover against champagne.py.

    python check_figures.py

Run from this folder inside a checkout of the site (it reads layouts/shortcodes and scripts/covers
two and three levels up) with Node on the PATH. The block between "math:pascal-p1" and its end must
be byte-identical in the two figures and the cover. It is run in Node, and its fill pours, its fill
events and its "Pascal's share minus what is kept above" decomposition are compared with
champagne.py's exact answers. Exits non-zero on any difference.
"""
import json
import pathlib
import re
import subprocess
import sys

from champagne import fill_events, triangle

HERE = pathlib.Path(__file__).resolve().parent
SITE = HERE.parents[2]
FILES = [SITE / "layouts/shortcodes/pascal-p1-champagne.html",
         SITE / "layouts/shortcodes/pascal-p1-rows.html",
         SITE / "scripts/covers/pascal-puzzles-the-champagne-tower.html"]
BLOCK = re.compile(r"// ---- math:pascal-p1 ----\n.*?// ---- end math:pascal-p1 ----\n", re.S)

failures = 0


def check(ok, what):
    global failures
    failures += not ok
    print(("ok    " if ok else "FAIL  ") + what)


blocks = [BLOCK.findall(f.read_text(encoding="utf-8")) for f in FILES]
check(all(len(b) == 1 for b in blocks), "each file holds the math block exactly once")
check(len({b[0] for b in blocks}) == 1, "the block is byte-identical in both figures and the cover")

ROWS = list(range(3, 11)) + [30, 40]
harness = blocks[0][0] + """
var out = {}, rows = %s;
rows.forEach(function (R) { var f = p1Fill(R); out[R] = { fill: f.fill, events: f.events.map(function (e) { return e.glasses; }) }; });
var seed = 7, worst = 0;
function rnd() { seed = (seed * 1103515245 + 12345) %% 2147483648; return seed / 2147483648; }
for (var k = 0; k < 2000; k++) {
  var R = 3 + Math.floor(rnd() * 8), P = rnd() * Math.pow(2, R), r = Math.floor(rnd() * R), c = Math.floor(rnd() * (r + 1));
  var d = p1Kept(R, P, r, c);
  worst = Math.max(worst, Math.abs(d.share - d.kept - d.inflow) / Math.max(1, d.share));
}
out.kept = worst;
console.log(JSON.stringify(out));
""" % json.dumps(ROWS)
version = subprocess.run(["node", "--version"], capture_output=True, text=True).stdout.strip()
js = json.loads(subprocess.run(["node", "-e", harness], capture_output=True, text=True, check=True).stdout)
print(f"   Node {version}")

for R in ROWS:
    ev = fill_events(triangle(R))
    index = {(r, c): r * (r + 1) // 2 + c for r in range(R) for c in range(r + 1)}
    exact = {index[g]: p for p, gs in ev for g in gs}
    got = js[str(R)]
    err = max(abs(got["fill"][i] - float(p)) / float(p) for i, p in exact.items())
    same_events = [sorted(index[g] for g in gs) for _, gs in ev] == [sorted(e) for e in got["events"]]
    check(err < 1e-12, f"{R} rows: every fill pour within {err:.1e} of the exact fraction")
    check(same_events, f"{R} rows: the same {len(ev)} fill events, each with the same glasses")
check(js["kept"] < 1e-9, f"share - kept = inflow on 2,000 random pours (worst {js['kept']:.1e})")

print(f"\n{failures} failed" if failures else "\nall checks passed")
sys.exit(1 if failures else 0)
