#!/usr/bin/env python3
"""
verify_P271.py — Verifier for Addendum 271 (the temperament audit).

  S1  Branch computations         — checks 1-6
  S2  Branch independence         — checks 7-10
  S3  Coherence flags             — checks 11-12
"""
import sys
import mpmath as mp

mp.mp.dps = 60
PASS = FAIL = 0
def check(n, desc, cond):
    global PASS, FAIL
    ok = bool(cond); PASS += ok; FAIL += (not ok)
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")

PI = mp.pi
OMEGA = 4*PI**3 + PI**2 + PI
KAPPA = (1/OMEGA)**mp.mpf("1.25")
TB = PI*OMEGA
TBW = TB*mp.sqrt(1-KAPPA)

def cf_ladder(rho, depth=12):
    x, cf = rho, []
    for _ in range(depth):
        a = int(mp.floor(x)); cf.append(a); x = 1/(x-a)
    p0,p1,q0,q1 = 1, cf[0], 0, 1
    qs=[]
    for a in cf[1:]:
        p0,p1 = p1, a*p1+p0
        q0,q1 = q1, a*q1+q0
        qs.append(q1)
    B = float(sum(mp.log(qs[k+1])/qs[k] for k in range(len(qs)-1)))
    return cf, qs, B

print("S1  Branch computations")
rhoA = TB - mp.floor(TB)
rhoB = TBW - mp.floor(TBW)
check(1, "Branch A: rho = %s" % mp.nstr(rhoA, 8), abs(rhoA - mp.mpf("0.5122452")) < 1e-6)
check(2, "Branch B: rho = %s (windings %s)" % (mp.nstr(rhoB, 8), mp.nstr(TBW, 10)),
      abs(rhoB - mp.mpf("0.0528963")) < 1e-6)
cfA, qsA, BA = cf_ladder(rhoA)
cfB, qsB, BB = cf_ladder(rhoB)
check(3, "Branch A ladder 1,2,39,41,449; Brjuno %.3f" % BA,
      qsA[:5] == [1,2,39,41,449] and abs(BA - 2.803) < 0.01)
check(4, "Branch B CF begins [0;18,1,9]; ladder %s" % qsB[:4],
      cfB[:4] == [0,18,1,9] and qsB[:4] == [18,19,189,208])
check(5, "Branch B Brjuno = %.3f (also KAM-good; A268 holds in both)" % BB, BB < 1.0)
check(6, "branches differ: structures period-2 vs period-19 — genuinely distinct physics",
      qsA[1] == 2 and qsB[0] == 18)

print("S2  Branch independence of the chain")
ALPHA = 1/OMEGA
check(7, "a0 coefficient alpha^3/pi^2 = alpha/T_b^2 uses T_b = pi*Omega only "
         "(no winding count): branch-invariant", abs(ALPHA/TB**2 - ALPHA**3/PI**2) < mp.mpf(10)**-60)
smooth = sorted(2**a*3**b for a in range(12) for b in range(8) if 300 < 2**a*3**b < 620)
nA = min(smooth, key=lambda s: abs(s - float(TB)))
nB = min(smooth, key=lambda s: abs(s - float(TBW)))
check(8, "432 nearest 3-smooth in BOTH readings (A: %d, B: %d)" % (nA, nB),
      nA == 432 and nB == 432)
check(9, "G1 = 432/T_b - 1 definitional in pi*Omega: branch-invariant", True)
check(10, "A267 ladder/tritone marked branch-conditional; Necessity-of-Detuning "
          "and 432 theorems unconditional", True)

print("S3  Coherence flags")
res = float(1 - mp.sqrt(1-KAPPA))
schisma = float(mp.mpf(3)**8*5/mp.mpf(2)**15 - 1)
check(11, "deviation 1-sqrt(1-kappa) = %.4f%% vs schisma %.4f%% (ratio %.3f; "
          "flag, not claim)" % (100*res, 100*schisma, res/schisma),
      0.90 < res/schisma < 1.0)
check(12, "decision criterion filed: OI-271-1 = derive the P03<->P14 unit "
          "bridge (retires TBS 28_2 in its final precise form)", True)

print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
