#!/usr/bin/env python3
"""
verify_P027.py -- Paper 27: the second observer.

This verifier checks the concrete reused geometry/arithmetic and flags the
places where interpretive observer/coherence claims are promoted to formal
derivations without enough mathematical structure in the TeX.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from verify_common import Verifier as _BaseVerifier, CheckResult


class Verifier(_BaseVerifier):
    """Output-layer normalization only: same checks, modern [PASS]/[FAIL] format."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        n = len(self.results)
        note, info = "", detail
        if not ok and "Expected" in detail:
            i = detail.find("Expected")
            note = " -- " + detail[i:]
            info = detail[:i].rstrip().rstrip(";")
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {label}{note}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return ok

    def summary(self):
        passed = sum(r.ok for r in self.results)
        failed = len(self.results) - passed
        print(f"\n{'='*60}\nRESULT: {passed} PASS / {failed} FAIL")
        return 1 if failed else 0


v = Verifier("P027 -- Second Observer")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "27_Paper_SecondObserver.tex").read_text()

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
MU1 = 16.0 * PI**3 / 5.0 + 3.0 * PI**2 / 4.0 + 2.0 * PI / 3.0
ALPHA = 1.0 / MU0

BULK = 4.0 * PI**3 / MU0
BOUNDARY = PI**2 / MU0
EDGE = PI / MU0
PLANCK_LOG = (3.0 * PI / 20.0) * MU1 / (1.0 - MU1 * ALPHA**2)


def pct(value: float) -> float:
    return 100.0 * value


v.check("density integral alpha inverse", MU0, 137.036, rel=3e-6)
v.check("bulk contribution 4*pi^3", 4.0 * PI**3, 124.025, rel=1e-5)
v.check("boundary contribution pi^2", PI**2, 9.8696, rel=5e-6)
v.check("edge contribution pi", PI, 3.1416, rel=3e-6)
v.check("bulk fraction percent", pct(BULK), 90.5, rel=7e-4)
v.check("boundary fraction percent", pct(BOUNDARY), 7.2, rel=4e-3)
v.check("edge fraction percent", pct(EDGE), 2.3, rel=5e-3)
v.check("layer fractions sum", BULK + BOUNDARY + EDGE, 1.0, rel=1e-14)
v.check("mu1 first moment", MU1, 108.716684, rel=3e-9)
v.check("Planck/electron log formula", PLANCK_LOG, 51.528, rel=4e-5)
v.check("three-observer minimum count", 3, 3, rel=0)
v.record(
    "single-observer C o P = I is unconstrained",
    "take $P$ to be any invertible map and $C = P^{-1}$" in TEX,
    computed="trivial inverse construction present",
    claimed="single-observer coherence places no state-space constraint",
)

v.record(
    "mutual-coherence definition has a live label",
    "\\label{def:mutual_coherence}" in TEX,
    computed="definition is referenced as def:mutual_coherence but no label is attached",
    claimed="Definition reference resolves",
    detail="Expected TeX/reference fail.",
)
v.record(
    "Hopf projection/collapse supply C o P = I",
    False,
    computed="the Hopf map S3 -> S2 is not invertible, so projection along fibers plus collapse onto the base does not by itself define inverse C and P on a shared state space",
    claimed="Hopf fibration provides canonical P and C compatible with mutual coherence",
    detail="Expected proof-status fail.",
)
v.record(
    "S3 uniqueness theorem proves canonical projection-collapse structure",
    False,
    computed="Poincare gives topological S3 from compact simply-connected 3-manifold assumptions; it does not construct observer operators or prove uniqueness of the proposed canonical C/P structure",
    claimed="S3 is the unique compact shared boundary supporting mutual coherence",
    detail="Expected proof-status fail.",
)
v.record(
    "B4 bulk is derived uniquely from S3 boundary",
    False,
    computed="the proof selects B4 by minimality/Occam language; it does not classify all 4-manifolds with S3 boundary or derive a physical minimality principle",
    claimed="B4 is the minimal observer bulk forced by S3",
    detail="Expected proof-status fail.",
)
v.record(
    "coefficients 16, 3, 2 are derived in P27",
    False,
    computed="P27 delegates the coefficient derivation to Paper 8 and gives interpretations of counts, not a standalone construction from observer coherence",
    claimed="coefficients count self-intersection configurations forced by the second observer",
    detail="Expected derivation fail.",
)
v.record(
    "layer fractions prove information partition",
    False,
    computed="the numeric fractions are correct, but no entropy/information measure or observer-state sigma-algebra is defined to justify private/shared/individual percentages",
    claimed="90.5/7.2/2.3 percent measure private/shared/individual information",
    detail="Expected interpretation-to-formalism fail.",
)
v.record(
    "three social observers derive Z3 lens-space family topology",
    False,
    computed="the majority/mediation argument motivates the number 3, but it does not construct L(3,1)=S3/Z3 as the unique quotient or derive fermion-family representations",
    claimed="three fermion families follow from minimal non-trivial social structure",
    detail="Expected proof-status fail.",
)
v.record(
    "Planck/electron formula measures consensus stacking",
    False,
    computed="the P17 numerical formula is reused, but no map is supplied from observer consensus depth to mass logarithms",
    claimed="Planck-to-electron mass ratio measures consensus stacking",
    detail="Expected interpretation-to-formula fail.",
)
v.record(
    "dark matter hidden-observer principle is mathematically testable here",
    False,
    computed="the paper supplies no dynamical model, stress-energy tensor, or lensing/structure prediction distinguishing hidden observers from ordinary dark matter models",
    claimed="dark matter is invisible witness",
    detail="Expected non-verifiable claim.",
)
v.record(
    "dark-energy proportionality predicts Lambda",
    False,
    computed="Lambda is only stated proportional to pi/alpha^-1; no proportionality constant, unit convention, or observed value calculation is given",
    claimed="cosmological constant from intersubjectivity",
    detail="Expected open/conjectural fail.",
)
v.record(
    "P vs NP claims are formal complexity results",
    False,
    computed="no computational model, reductions, verifier language, or proof separating P and NP is supplied",
    claimed="from bulk P=NP; from boundary P!=NP",
    detail="Expected proof-status fail.",
)
v.record(
    "Big Bang as first disagreement is derived from equations",
    False,
    computed="the section is a conceptual reinterpretation; it does not derive FLRW dynamics, perturbations, nucleosynthesis, or CMB observables from observer disagreement",
    claimed="Big Bang was the first disagreement",
    detail="Expected physics-derivation fail.",
)
v.record(
    "complete Level -1 foundation is established",
    False,
    computed="the paper gives a coherent narrative but leaves the operator, topology, information, and cosmology bridges as assertions or conjectures",
    claimed="foundation beneath the geometric TOE",
    detail="Expected status fail.",
)

sys.exit(v.summary())
