"""Checks and the report behind every number in Part 1 of the Pascal puzzles (the champagne tower).

    python test_champagne.py

Exits non-zero if any check fails. Standard library only.
"""
import math
import random
import statistics
import sys
import time
from fractions import Fraction

from champagne import (ancestors, champagne_tower, cone_formula, fill_events, fill_pour_by_bisection,
                       fill_pours, kept_formula, levels, pascal_flow, pour, square_pyramid, triangle)

failures = 0


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


def show(f):
    return str(f) if f.denominator < 10 ** 4 else f"{float(f):.4f}"


rng = random.Random(1)

print("== The interview version against the general tower")
T12 = triangle(12)
ok = True
for _ in range(300):
    p = rng.choice([rng.randint(0, 200), rng.uniform(0, 4000)])
    r = rng.randrange(12)
    c = rng.randrange(r + 1)
    ok &= champagne_tower(p, r, c) == levels(T12, p, number=float)[(r, c)]
check(ok, "champagne_tower() == levels() in doubles, 300 random pours on 12 rows")

print("\n== Bottomless glasses are Pascal's triangle")
for p in (1, 7, 100, Fraction(355, 113)):
    inflow, _ = pour(T12, p, capacity={g: 0 for g in T12[0]})
    check(inflow == pascal_flow(12, p), f"capacity 0, pour {p}: every glass gets pour * C(r, c) / 2^r")

print("\n== Glasses of capacity 1: Pascal minus what the glasses above keep")
ok = True
for p in [Fraction(rng.randint(0, 3000), rng.randint(1, 7)) for _ in range(40)]:
    inflow, _ = pour(T12, p)
    ok &= inflow == kept_formula(12, p, levels(T12, p))
check(ok, "inflow(r,c) = pour*C(r,c)/2^r - sum of level(i,j)*C(r-i,c-j)/2^(r-i), exactly, 40 pours on 12 rows")

print("\n== Fill pours by events, verified exactly")
fp12 = fill_pours(T12)
ok = True
for g, t in fp12.items():
    inflow, _ = pour(T12, t)
    before = levels(T12, t - Fraction(1, 10 ** 9))[g]
    ok &= inflow[g] == 1 and before < 1
check(ok, "for every glass of 12 rows: at its fill pour it has received exactly 1, a billionth earlier less than 1")
T6 = triangle(6)
fp6 = fill_pours(T6)
ok = True
for g, t in fp6.items():
    lo, hi = fill_pour_by_bisection(T6, g, steps=50)
    ok &= lo < t <= hi
check(ok, "bisection (50 halvings, exact arithmetic) brackets every fill pour of 6 rows")
print("   fill pours, rows 0-9:")
fp10 = fill_pours(triangle(10))
for r in range(10):
    print(f"   row {r}: " + ", ".join(show(fp10[(r, c)]) for c in range(r + 1)))

print("\n== The edges")
fp30 = fill_pours(triangle(30))
check(all(fp30[(r, 0)] == fp30[(r, r)] == 2 ** (r + 1) - 1 for r in range(30)),
      "the edge glasses of row r fill at 2^(r+1) - 1, rows 0-29")

print("\n== The formula that assumes every glass above is full")
holds = fails = 0
first_fail = None
for r in range(30):
    for c in range(r + 1):
        t, guess = fp30[(r, c)], cone_formula(r, c)
        if all(fp30[a] <= t for a in ancestors(r, c)):
            holds += guess == t
            if guess != t:
                check(False, f"formula should hold at {(r, c)}")
        else:
            fails += guess > t
            first_fail = first_fail or (r, c)
check(holds + fails == len(fp30), f"30 rows: the formula is exact on the {holds} glasses whose ancestors are all full "
      f"when they fill, and too high on the other {fails}")
g = first_fail
late = [a for a in ancestors(*g) if fp30[a] > fp30[g]]
print(f"   first glass where it fails: {g}, fills at {fp30[g]}, formula says {cone_formula(*g)}, "
      f"still filling above it: {late}, which fill at {[str(fp30[a]) for a in late]}")
held = levels(triangle(5), fp30[g])[late[0]]
check(held == Fraction(5, 6) and cone_formula(*g) - fp30[g] == Fraction(1, 3),
      f"when {g} fills, {late[0]} holds {held}: the 1/6 it doesn't keep is worth 1/3 of pour")

print("\n== A 10-row tower, 55 glasses")
T10 = triangle(10)
ev10 = fill_events(T10)
last = ev10[-1][0]
check(last == 1023 and pour(T10, last)[1] == 968, "the last glasses fill at 1023 poured, with 968 on the table")
mid = fp10[(9, 4)]
check(mid == fp10[(9, 5)] == Fraction(100, 3), "the two middle glasses of the bottom row fill at 100/3")
print(f"   full when they fill: {sum(1 for t in fp10.values() if t <= mid)} of 55, fill events: {len(ev10)}")
lv = levels(T10, 55)
_, table = pour(T10, 55)
print(f"   pour exactly 55: {sum(1 for v in lv.values() if v == 1)} glasses full, {sum(lv.values())} "
      f"= {float(sum(lv.values()))} held, {table} = {float(table)} on the table")
check(sum(1 for v in lv.values() if v == 1) == 37 and table == Fraction(915, 64), "pour 55: 37 full, 915/64 on the table")
order = [(str(p), gs) for p, gs in ev10[:9]]
print(f"   the first nine fill events: {order}")

print("\n== Doubles against exact, 30 rows")
t0 = time.perf_counter()
ex = fill_events(triangle(30))
t_exact = time.perf_counter() - t0
fl = fill_events(triangle(30), number=float)
ffl = {g: p for p, gs in fl for g in gs}
err = max(abs(ffl[g] - float(t)) / float(t) for g, t in fp30.items())
check(err < 1e-15, f"largest relative error in a fill pour: {err:.2e}")
print(f"   events: exact {len(ex)}, doubles {len(fl)}; exact run took {t_exact:.2f} s")
exact_sets = {frozenset(gs) for _, gs in ex}
for p, gs in fl:
    if frozenset(gs) not in exact_sets:
        print(f"   doubles fill {gs} at {p!r}")
for p, gs in ex:
    if frozenset(gs) not in {frozenset(x) for _, x in fl}:
        print(f"   exact fills {gs} together at {p}")

print(f"   largest denominator of a fill pour in 30 rows: {max(t.denominator for t in fp30.values())}")
ex40 = fill_events(triangle(40))
gap, a = min(((ex40[i + 1][0] - ex40[i][0]) / ex40[i][0], i) for i in range(len(ex40) - 1))
b = a + 1
print(f"   40 rows, {len(ex40)} events; the two closest: {ex40[a][1]} at {ex40[a][0]} = {float(ex40[a][0]):.2f} and "
      f"{ex40[b][1]} at {ex40[b][0]}, {float(gap):.1e} apart (relative)")
check(ex40[b][0] == 2 ** 34 - 1 and ex40[a][0] == Fraction(566935683035, 33),
      "glass (38, 1) fills at 566935683035/33, just before the edges of row 33 at 2^34 - 1")

print("\n== Middle against edge, 100 rows in doubles")
t0 = time.perf_counter()
fp100 = fill_pours(triangle(100), number=float)
print(f"   (took {time.perf_counter() - t0:.1f} s)")
first = [min(fp100[(r, c)] for c in range(r + 1)) for r in range(100)]
check(all(min(range(r + 1), key=lambda c: fp100[(r, c)]) in (r // 2, (r + 1) // 2) for r in range(100)),
      "in every row up to 99 the middle glass is the first to fill")
xs = [math.log(r) for r in range(50, 100)]
ys = [math.log(first[r]) for r in range(50, 100)]
mx, my = statistics.mean(xs), statistics.mean(ys)
slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
print(f"   middle of row 99 fills at {first[99]:.2f}; log-log slope over rows 50-99: {slope:.3f}; "
      f"fill / r^1.5 at rows 25, 50, 99: {[round(first[r] / r ** 1.5, 3) for r in (25, 50, 99)]}")
for r in (11, 20, 39, 99):
    print(f"   row {r}: middle fills at {first[r]:.2f}, with {r * (r + 1) // 2} glasses above it; edges at {2 ** (r + 1) - 1}")
P = first[99]
width = [sum(1 for c in range(i + 1) if fp100[(i, c)] <= P) for i in range(100)]
print(f"   when it fills: {sum(width)} glasses full; full glasses per row at rows 4, 16, 36, 64, 99: "
      f"{[width[i] for i in (4, 16, 36, 64, 99)]}; widest row holds {max(width)}")

print("\n== Real towers are square pyramids")
for layers in range(1, 7):
    sp = fill_pours(square_pyramid(layers))
    check(max(sp.values()) == sp[(layers - 1, 0, 0)] == Fraction(4 ** layers - 1, 3),
          f"{layers} layers, {len(sp)} glasses: the corners fill last, at (4^{layers} - 1)/3 = {(4 ** layers - 1) // 3}")
S5 = square_pyramid(5)
sp5 = fill_pours(S5)
print(f"   5 layers: first bottom glass at {min(t for g, t in sp5.items() if g[0] == 4)}, "
      f"table at 341: {pour(S5, 341)[1]}")

print("\n== Glasses of different sizes")
cap = {g: 2 for g in T10[0]}
check(fill_pours(T10, cap) == {g: 2 * t for g, t in fp10.items()}, "every glass twice as big: every fill pour doubles")
cap = {g: (Fraction(1, 2) if g[0] == 9 else 1) for g in T10[0]}
check(fill_pours(T10, cap)[(9, 0)] == 2 ** 9 - 1 + Fraction(2 ** 9, 2),
      "half-size bottom row: its corners fill at 2^9 - 1 + 2^9/2 = 767")

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