#!/usr/bin/env python3
"""047 -- The Coat Fits Everyone: rerunnable handle.

Standard library only for the mathematics (exact rationals, deterministic, ASCII output);
part 8 additionally runs the page's own inline script under Node and verifies its real input grid.
Exit 0 only if every part of the claim holds AND every mutant is caught.

The claim, in the order it is checked:
  1. what a shared memory says cancels out of the difference between two readers
  2. a partial read (0 < lam < 2, lam != 1) forgets the start geometrically, never exactly
  3. a read at face value (lam = 1) forgets it exactly, in one step, and is the only such value
  4. for a DIAGONALISABLE map whose other eigenvalues are smaller than 1 in size, what survives
     reading is the eigenvalue-1 part of the difference, and the rest is bounded by K * rho^n
  4b. outside that class the statement is false: a defective eigenvalue 1 grows, -1 flips, 3/2 expands
  5. a first-person note stored in a contracted coordinate hands every reader the same name
  6. at face value a note keyed to a fixed coordinate is taken by its owner or by nobody;
     partial trust still selects one owner but can make its moving name collide with another name
  7. mutants: each check above is shown to FAIL on a broken version of what it guards
  8. the rig on the page agrees with the handle; neighbour-counting and unreachable-control mutants are caught
"""
import pathlib
import random
import subprocess
import sys
import tempfile
from fractions import Fraction as F

failures = []


def check(ok, label, got=None, want=None):
    mark = "ok" if ok else "FAIL"
    suffix = "" if got is None else f" got={got!r} want={want!r}"
    print(f"  {mark:4} {label}{suffix}")
    if not ok:
        failures.append(label)


# ---------- exact linear algebra over the rationals ----------

def matmul(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))]
            for i in range(len(a))]


def matvec(a, v):
    return [sum(a[i][k] * v[k] for k in range(len(v))) for i in range(len(a))]


def inverse(m):
    n = len(m)
    a = [[F(x) for x in row] + [F(int(i == j)) for j in range(n)] for i, row in enumerate(m)]
    for col in range(n):
        piv = next((r for r in range(col, n) if a[r][col] != 0), None)
        if piv is None:
            raise ValueError("singular")
        a[col], a[piv] = a[piv], a[col]
        p = a[col][col]
        a[col] = [x / p for x in a[col]]
        for r in range(n):
            if r != col and a[r][col] != 0:
                f = a[r][col]
                a[r] = [x - f * y for x, y in zip(a[r], a[col])]
    return [row[n:] for row in a]


def diag(values):
    n = len(values)
    return [[F(values[i]) if i == j else F(0) for j in range(n)] for i in range(n)]


def sub(u, v):
    return [x - y for x, y in zip(u, v)]


def dot(u, v):
    return sum(x * y for x, y in zip(u, v))


def rand_vec(rng, n, span=9):
    return [F(rng.randint(-span, span), rng.randint(1, 7)) for _ in range(n)]


# ---------- the reading map ----------

def read(x, m, lam):
    """One read of memory item m at trust lam: x <- (1 - lam) x + lam m."""
    return [(1 - lam) * xi + lam * mi for xi, mi in zip(x, m)]


def difference_follows_law(x, y, items_x, items_y, lams):
    """True iff, after every read, x - y equals prod(1 - lam) * (x0 - y0)."""
    d0, factor = sub(x, y), F(1)
    for mx, my, lam in zip(items_x, items_y, lams):
        x, y = read(x, mx, lam), read(y, my, lam)
        factor *= (1 - lam)
        if sub(x, y) != [factor * d for d in d0]:
            return False
    return True


rng = random.Random(47)
print("047 -- The Coat Fits Everyone - handle\n")

# 1. the content cancels
print("1. what the memory says cancels out of the difference")
ok_all = True
for _ in range(200):
    x, y = rand_vec(rng, 4), rand_vec(rng, 4)
    lams = [F(rng.randint(1, 19), 10) for _ in range(12)]
    items = [rand_vec(rng, 4) for _ in range(12)]
    ok_all &= difference_follows_law(x, y, items, items, lams)
check(ok_all, "200 random pairs, 12 shared reads each: x-y = prod(1-lam) (x0-y0), exactly")
x, y = rand_vec(rng, 4), rand_vec(rng, 4)
lams = [F(1, 2)] * 10
traj = []
for trial in range(2):
    a, b, row = x[:], y[:], []
    for _ in range(10):
        m = rand_vec(rng, 4)
        a, b = read(a, m, lams[0]), read(b, m, lams[0])
        row.append(sub(a, b))
    traj.append(row)
check(traj[0] == traj[1], "two unrelated memories give the identical difference trajectory")

# 2. partial trust forgets geometrically, never exactly
print("\n2. a partial read forgets the start geometrically, never exactly")
d = F(7, 3)
never_zero, always_shrinks = True, True
for num in range(1, 20):
    lam = F(num, 10)
    if lam == 1:
        continue
    gap, prev = d, d
    for _ in range(60):
        gap = abs(1 - lam) * gap
        never_zero &= gap != 0
        always_shrinks &= gap < prev
        prev = gap
check(never_zero, "lam in {0.1..1.9} minus {1}: the gap is never exactly zero in 60 reads")
check(always_shrinks, "and it strictly shrinks at every read (|1-lam| < 1)")
gap, n = d, 0
while gap >= F(1, 10**6):
    gap, n = gap / 2, n + 1
check(n == 22, "at lam = 1/2 a gap of 7/3 first drops below 1e-6 at read", n, 22)
check(abs(1 - F(21, 10)) > 1 and abs(1 - F(-1, 10)) > 1,
      "outside 0 < lam < 2 the factor exceeds 1: the readers separate")

# 3. face value is the one exact case
print("\n3. a read at face value forgets it in one step, and only then")
one_step = True
for _ in range(200):
    x, y, m = rand_vec(rng, 4), rand_vec(rng, 4), rand_vec(rng, 4)
    one_step &= read(x, m, F(1)) == read(y, m, F(1)) == m
check(one_step, "lam = 1: after ONE read both readers hold exactly the note, from any start")
exact = [F(num, 100) for num in range(1, 200) if (1 - F(num, 100)) == 0]
check(exact == [F(1)], "on the grid 0.01..1.99 the only lam with 1 - lam = 0 is", exact, [F(1)])

# 4. what survives is the eigenvalue-1 part
print("\n4. diagonalisable map, other eigenvalues inside the unit disc: the eigenvalue-1 part survives")
while True:
    P = [[F(rng.randint(-3, 3)) for _ in range(5)] for _ in range(5)]
    try:
        Pinv = inverse(P)
        break
    except ValueError:
        continue
mus = [F(1), F(1), F(1, 2), F(-1, 3), F(2, 5)]
A = matmul(matmul(P, diag(mus)), Pinv)
PROJ = matmul(matmul(P, diag([1, 1, 0, 0, 0])), Pinv)
x, y = rand_vec(rng, 5), rand_vec(rng, 5)
d0 = sub(x, y)
left_fixed = [Pinv[0], Pinv[1]]          # rows of P^-1 for eigenvalue 1: l A = l
left_other = Pinv[2]                     # a left eigenvector for 1/2
exact_split, conserved, lost, cur_x, cur_y = True, True, False, x[:], y[:]
power = diag([1] * 5)
for step in range(1, 41):
    b = rand_vec(rng, 5)                 # the same memory item for both readers
    cur_x = [u + v for u, v in zip(matvec(A, cur_x), b)]
    cur_y = [u + v for u, v in zip(matvec(A, cur_y), b)]
    power = matmul(power, diag(mus))
    want = matvec(matmul(matmul(P, power), Pinv), d0)
    exact_split &= sub(cur_x, cur_y) == want
    conserved &= all(dot(l, sub(cur_x, cur_y)) == dot(l, d0) for l in left_fixed)
    lost |= dot(left_other, sub(cur_x, cur_y)) != dot(left_other, d0)
residual = max(abs(v) for v in sub(sub(cur_x, cur_y), matvec(PROJ, d0)))
# The bound is derived, not guessed: the largest non-unit |mu| is 1/2, so the forgotten part is
# at most K * (1/2)^n, with K read off P and the coordinates of d0 in the forgotten directions.
coords = matvec(Pinv, d0)
K = max(sum(abs(P[i][j]) * abs(coords[j]) for j in (2, 3, 4)) for i in range(5))
check(exact_split, "40 reads: x-y = P D^n P^-1 (x0-y0), exactly, whatever was read")
check(conserved, "both eigenvalue-1 functionals of the difference are conserved, exactly")
check(lost, "a functional off the fixed part is NOT conserved (it is the one being forgotten)")
check(0 < residual <= K * F(1, 2**40),
      "after 40 reads what is left of the rest is within K (1/2)^40 of zero, and not yet zero",
      float(residual), f"<= {float(K * F(1, 2**40)):.3e}")
check(matvec(PROJ, d0) != [F(0)] * 5, "and that projection is not zero: THIS pair of readers stays two")
# The pair stays apart only because it differed along a fixed direction to begin with. A pair whose
# difference has no fixed part converges completely -- conservation is of the difference, for all
# starts, and says nothing about distinguishing two readers who never differed there.
twin = [u + v for u, v in zip(x, matvec(P, [F(0), F(0), F(3), F(-2), F(5)]))]
gap = sub(x, twin)
check(matvec(PROJ, gap) == [F(0)] * 5 and all(dot(l, gap) == 0 for l in left_fixed),
      "a pair differing only in the forgotten directions has NO fixed part: nothing keeps it apart")

# 4b. OUTSIDE the tested class the statement is false, and the handle says so. [Codex bot P1 and Sol on
# strange-attractor#47: the first version claimed this for "any linear way of reading"; both handles
# only ever built diagonalisable maps with the other eigenvalues inside the unit disc.]
print("\n4b. outside that class it fails (negative controls for the scope of the claim)")
J = [[F(1), F(1), F(0)], [F(0), F(1), F(0)], [F(0), F(0), F(1, 2)]]      # eigenvalue 1 repeated, not diagonalisable
v = [F(0), F(1), F(0)]
for _ in range(40):
    v = matvec(J, v)
check(v == [F(40), F(1), F(0)],
      "defective eigenvalue 1, every other eigenvalue 1/2: A^40 (0,1,0) = (40,1,0) -- the difference GROWS",
      [str(c) for c in v], ["40", "1", "0"])
R = [[F(1), F(0)], [F(0), F(-1)]]                                          # an eigenvalue of size 1 that is not 1
w, seen_w = [F(1), F(1)], []
for _ in range(4):
    w = matvec(R, w)
    seen_w.append(tuple(w))
check(seen_w == [(F(1), F(-1)), (F(1), F(1))] * 2,
      "eigenvalue -1: the difference neither shrinks nor settles, it flips for ever")
E = [[F(1), F(0)], [F(0), F(3, 2)]]                                        # an eigenvalue outside the unit disc
z = [F(1), F(1)]
for _ in range(10):
    z = matvec(E, z)
check(z[1] == F(3, 2) ** 10 and z[1] > 57,
      "eigenvalue 3/2: the difference expands (factor 57.67 after ten reads)")

# 5 and 6. the coat and the passport
print("\n5. a first-person note in a contracted coordinate: the coat fits everyone")


def unique_winner(names):
    """015's election: a leader exists iff exactly one hand holds the maximal name."""
    return sum(1 for v in names if v == max(names)) == 1


def wear(names, note_name, lam):
    """An unkeyed 'my name is N' note: every reader applies it to itself."""
    return [(1 - lam) * v + lam * note_name for v in names]


def stamp(hands, note_key, note_name, lam=F(1)):
    """A keyed note: applied only by the matching hand, at the stated trust. Keys are never written."""
    return [(key, (1 - lam) * name + lam * note_name if key == note_key else name)
            for key, name in hands]


names = [F(v) for v in (3, 11, 5, 8, 2, 13)]
check(unique_winner(names) and len(set(names)) == 6, "before reading: six hands, six names, one leader")
worn = wear(names, F(40), F(1))
check(len(set(worn)) == 1, "after ONE face-value read of an unkeyed note: distinct names =",
      len(set(worn)), 1)
check(not unique_winner(worn), "and the election has no leader: all six hold the maximal name")
half, resolution, reads = names[:], F(1, 1000), 0
spread0 = max(names) - min(names)                  # 13 - 2 = 11
while max(half) - min(half) >= resolution:
    half, reads = wear(half, F(40), F(1, 2)), reads + 1
check(len(set(half)) == 6, "at lam = 1/2 the six names stay distinct in exact arithmetic")
# Derived: the spread is 11 / 2^n, so the first n with 11 / 2^n < 1/1000 is 14 (2^14 = 16384).
check(reads == 14 and spread0 / 2**13 >= resolution > spread0 / 2**14,
      "but a reader with resolution 1/1000 cannot tell them apart from read", reads, 14)

print("\n6. a note keyed to a fixed coordinate: its owner takes it, or nobody does")
hands = [(key, name) for key, name in zip((101, 102, 103, 104, 105, 106), names)]
stamped = hands
for _ in range(25):
    stamped = stamp(stamped, 104, F(40))
after = [name for _, name in stamped]
check([k for k, _ in stamped] == [k for k, _ in hands], "25 reads later every key is unchanged")
check(sum(1 for v in after if v == F(40)) == 1 and stamped[3][1] == F(40),
      "exactly one hand wears the name: the one whose key the note carries")
check(len(set(after)) == 6 and unique_winner(after),
      "at face value: six names, one leader, no luck required")
collision = [name for _, name in stamp(hands, 104, F(40), F(3, 32))]
check(collision == [F(3), F(11), F(5), F(11), F(2), F(13)]
      and len(set(collision)) == 5 and unique_winner(collision),
      "partial trust 3/32: the selected name meets 11, so only five names remain")
tied_leader = [name for _, name in stamp(hands, 104, F(40), F(5, 32))]
check(tied_leader == [F(3), F(11), F(5), F(13), F(2), F(13)]
      and len(set(tied_leader)) == 5 and not unique_winner(tied_leader),
      "partial trust 5/32: the selected name meets 13, so the leader is no longer unique")
orphan = hands
for _ in range(25):
    orphan = stamp(orphan, 999, F(40))
check(orphan == hands, "a note whose owner is not in the room is worn by nobody")

# 7. mutants: every guard is seen failing
print("\n7. mutants (a check that cannot fail is not a check)")
x, y = rand_vec(rng, 4), rand_vec(rng, 4)
lams = [F(1, 2)] * 6
shared = [rand_vec(rng, 4) for _ in range(6)]
private = [rand_vec(rng, 4) for _ in range(6)]
check(difference_follows_law(x, y, shared, shared, lams)
      and not difference_follows_law(x, y, shared, private, lams),
      "readers of DIFFERENT memories break the law of check 1 (caught)")
leaky = matmul(matmul(P, diag([F(9, 10), F(1), F(1, 2), F(-1, 3), F(2, 5)])), Pinv)
check(dot(Pinv[0], matvec(leaky, d0)) != dot(Pinv[0], d0) and dot(Pinv[0], matvec(A, d0)) == dot(Pinv[0], d0),
      "an 'identity' coordinate with eigenvalue 9/10 is not conserved (caught)")
careless = [(key, F(40)) for key, _ in hands]       # the key check removed
check(len({name for _, name in careless}) == 1 and len({name for _, name in stamped}) == 6,
      "a passport applied without reading the key is the coat again (caught)")
check(unique_winner([F(1), F(2), F(3)]) and not unique_winner([F(3), F(2), F(3)]),
      "the election detector itself tells a unique maximum from a shared one")

# 8. the page itself: its inline script is run and must agree with the numbers above
print("\n8. the rig on the page says what this handle says")
HERE = pathlib.Path(__file__).resolve().parent
PAGE = HERE / "index.html"
RIG_TEST = HERE / "rig_test.js"
GOOD = "if(s[i]-first>=RES){c+=1;first=s[i];}"
NEIGHBOUR = "if(s[i]-s[i-1]>=RES){c+=1;}"          # the first rig: counts neighbours, says 12
FINE_STEP = 'step="0.00625"'
COARSE_STEP = 'step="0.05"'                         # cannot select 3/32 or 5/32


def run_rig(page_path):
    try:
        proc = subprocess.run(["node", str(RIG_TEST), str(page_path)], check=False,
                              capture_output=True, text=True, timeout=120)
    except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
        return None, type(exc).__name__
    return proc.returncode, proc.stdout


page_text = PAGE.read_text(encoding="utf-8")
check(page_text.count(GOOD) == 1, "the page counts names by 'can any two be separated'")
check(page_text.count(FINE_STEP) == 1, "the published slider has the exact 1/160 input grid")
code, out = run_rig(PAGE)
check(code == 0 and (out or "").count("\nok ") + (out or "").startswith("ok ") >= 30 and "FAIL" not in (out or ""),
      "Node runs the page's script: 30+ expectations hold (reachable exact collisions, addressed modes, no false '0 exactly')",
      code if code is not None else out, 0)
with tempfile.TemporaryDirectory() as tmp:
    mutant = pathlib.Path(tmp) / "index.html"
    mutant.write_text(page_text.replace(GOOD, NEIGHBOUR), encoding="utf-8", newline="\n")
    mcode, mout = run_rig(mutant)
check(mcode == 1 and "got=12 want=14" in (mout or ""),
      "mutant: the neighbour-counting rig is caught saying 12 (caught)",
      mcode if mcode is not None else mout, 1)
with tempfile.TemporaryDirectory() as tmp:
    mutant = pathlib.Path(tmp) / "index.html"
    mutant.write_text(page_text.replace(FINE_STEP, COARSE_STEP), encoding="utf-8", newline="\n")
    mcode, mout = run_rig(mutant)
check(mcode == 1 and "slider can select exact 3/32 got=false want=true" in (mout or ""),
      "mutant: a coarse slider grid cannot hide unreachable exact controls (caught)",
      mcode if mcode is not None else mout, 1)

print()
if failures:
    print(f"claim does NOT hold: {len(failures)} failing check(s)")
    for label in failures:
        print(f"  - {label}")
    sys.exit(1)
print("claim holds: True")
