#!/usr/bin/env python3
"""check_card.py -- the exact arithmetic of the UFT reader card.
Exact arithmetic (sympy, integers). Prints one PASS/FAIL line per check, then COUNT and RESULT, with LF line ends.
The card is a compact reader fixture; the theorems and their receipt are in unified_field_theory and check_uft.py."""
import sys
import sympy as sp

sys.stdout.reconfigure(newline="\n")
OK = True
LABELS = []


def line(label, cond):
    global OK
    cond = bool(cond)
    OK = OK and cond
    LABELS.append((label, cond))
    print(("PASS " if cond else "FAIL ") + label)


def inertia(M):
    """(positive, negative, zero) eigenvalue counts of a real symmetric matrix, exact, by Descartes on the characteristic polynomial."""
    lam = sp.symbols("lam")
    c = sp.Poly(M.charpoly(lam).as_expr(), lam).all_coeffs()
    z = 0
    while c and c[-1] == 0:
        c.pop()
        z += 1
    ch = lambda cs: sum(1 for a, b in zip([x for x in cs if x != 0], [x for x in cs if x != 0][1:]) if a * b < 0)
    pos = ch(c)
    neg = ch([x * (-1) ** (len(c) - 1 - i) for i, x in enumerate(c)])
    return (pos, neg, z)


def dsum(A, B):
    M = sp.zeros(A.shape[0] + B.shape[0])
    M[:A.shape[0], :A.shape[0]] = A
    M[A.shape[0]:, A.shape[0]:] = B
    return M


I2 = sp.eye(2)
Q = sp.Matrix([[1, 1], [1, 0]])
Om = sp.Matrix([[0, 1], [-1, 0]])
C1 = -Om
G = Q * Om - Om * Q
eta = dsum(G, I2)
th = sp.symbols("theta", real=True)
Rth = sp.cos(th) * I2 + sp.sin(th) * C1
Sig = lambda A: A.T * G * A - G
eq = lambda A, B: all(sp.simplify(e) == 0 for e in (A - B))
addr = {(q, u): (137 * q + 4 * u) % 548 for q in range(4) for u in range(137)}
TARGETS = {"golden": (129, 1, 135), "burgundy": (18, 2, 73), "powder blue": (353, 1, 54)}  # the card's declared table: name -> (A, q*, u*)


def card_preds(targets, packed):
    r = {}
    r["marks"] = all((137 * q + 4 * u) % 548 == A and addr[(q, u)] == A and ((A % 4), ((A - 137 * (A % 4)) // 4) % 137) == (q, u) for A, q, u in targets.values())
    r["distinct"] = len({t[0] for t in targets.values()}) == 3 and len({t[1:] for t in targets.values()}) == 3
    agree = sorted(k for k in addr if addr[k] == packed[k])
    r["packed"] = all((addr[k] - packed[k] - 3 * k[1]) % 548 == 0 for k in addr) and agree == [(q, 0) for q in range(4)]
    return r, agree


P_idx = {(q, u): 137 * q + u for q in range(4) for u in range(137)}
pr, agree = card_preds(TARGETS, P_idx)
print("# P. Reader card: exact arithmetic")
line("P1 step 5: the sign of the G corner flips the signature of eta^ from (3, 1) to (4, 0); step 7: eta^ has signature (3, 1)", inertia(dsum(sp.Matrix([[2, 1], [1, 2]]), I2)) == (4, 0, 0) and inertia(eta) == (3, 1, 0))
line("P2 step 6: U = cos(theta) I - sin(theta) Omega equals e^{theta C1}", eq(sp.cos(th) * I2 - sp.sin(th) * Om, Rth))
line("P3 step 6: the half turn theta = pi gives U = -I and Sigma_G(U) = 0", eq(sp.cos(sp.pi) * I2 - sp.sin(sp.pi) * Om, -I2) and Sig(-I2) == sp.zeros(2))
line("P4 colour addresses (declared table): " + "; ".join("%s A = %d = (q*, u*) = (%d, %d)" % (n, A, q, u) for n, (A, q, u) in TARGETS.items()) + "; each satisfies 137 q* + 4 u* = A mod 548 and is the inverse image of A", pr["marks"])
line("P5 the three marks are distinct addresses and distinct pairs", pr["distinct"])
line("P6 with P = 137 q + u the packed index (u = 0..136), A - P = 3u (mod 548) on all 548 pairs; A = P exactly at u = 0, the four states {%s}" % ", ".join(str(addr[k]) for k in agree), pr["packed"] and [addr[k] for k in agree] == [0, 137, 274, 411])
print("# Q. One-fault controls of the card")
bad_t = dict(TARGETS, golden=(130, 1, 135))
line("Q1 the golden mark moved to A = 130: the card audit fails {%s}; target marks is among them" % ", ".join(k for k, v in card_preds(bad_t, P_idx)[0].items() if not v), not card_preds(bad_t, P_idx)[0]["marks"] and card_preds(bad_t, P_idx)[0]["distinct"])
bad_p = {k: addr[k] for k in addr}
line("Q2 the packed index replaced by the address itself: the card audit fails {%s}; target packed is among them" % ", ".join(k for k, v in card_preds(TARGETS, bad_p)[0].items() if not v), not card_preds(TARGETS, bad_p)[0]["packed"])
n_pass = sum(1 for _, v in LABELS if v)
print("COUNT PASS=%d FAIL=%d" % (n_pass, len(LABELS) - n_pass))
print("RESULT " + ("PASS" if OK else "FAIL"))
