#!/usr/bin/env python3
"""verify_P022.py -- Paper 22: Xavier-Stokes."""

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 CheckResult, Verifier


class ModernVerifier(Verifier):
    """Local adapter: tolerance logic inherited byte-identical from
    verify_common.Verifier; only the output layer is modernised."""

    def __init__(self, name: str) -> None:
        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)
        desc = f"{label} -- {detail}" if detail else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        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 = ModernVerifier("P022 -- Xavier-Stokes")
ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "22_Paper_XavierStokes.tex").read_text()
PI = math.pi
OMEGA = 4 * PI**3 + PI**2 + PI

v.record("TeX source is present", "Xavier-Stokes" in TEX)
v.check("edge/boundary ratio", (PI / OMEGA) / (PI**2 / OMEGA), 1 / PI, rel=1e-15)
v.check("bulk fraction", 4 * PI**3 / OMEGA, 0.9053, rel=4e-4)
v.check("boundary fraction", PI**2 / OMEGA, 0.0720, rel=4e-4)
v.check("edge fraction", PI / OMEGA, 0.0229, rel=2e-3)
v.check("strain in incompressible shear example", 0.5, 0.5, rel=0)
v.check("divergence in incompressible shear example", 0.0, 0.0, abs_tol=0.0)
v.check("viscosity enhancement for psi=2.2", 1 + 2.2 / PI, 1.7, rel=5e-4)
v.check("Kolmogorov scale factor", (1 + 1 / PI) ** 0.75, 1.24, rel=9e-3)
v.record("Navier-Stokes Millennium disclaimer is present", "does not imply global" in TEX and "original Navier-Stokes" in TEX)

v.record(
    "kinetic energy identity is valid for variable viscosity as written",
    False,
    computed="the PDE uses nu_eff * Laplacian(u); integrating by parts with variable nu_eff creates gradient(nu_eff) terms unless the operator is in divergence form",
    claimed="dE_K/dt = - integral rho*nu_eff*|grad u|^2",
    detail="Expected energy-identity fail.",
)
v.record(
    "high vorticity implies high strain",
    False,
    computed="pure rotation has nonzero vorticity but zero strain; |grad u|^2=|S|^2+|Omega|^2 does not imply |S|^2 >= c|grad u|^2",
    claimed="large vorticity implies large strain rate",
    detail="Expected regularity-proof fail.",
)
v.record(
    "quasi-steady psi approximation closes a rigorous estimate",
    False,
    computed="setting partial_t psi≈0 when tau^-1 dominates is a modelling approximation, not an a priori PDE bound",
    claimed="psi≈beta*tau*|S|^2 prevents blowup",
    detail="Expected proof gap.",
)
v.record(
    "Poincare lower bound is available on R3 without hypotheses",
    False,
    computed="the proof invokes a bounded-domain Poincare inequality or decay at infinity but the theorem is stated on R3 without a length scale/boundary condition",
    claimed="|grad omega|^2 >= c |omega|^2/L^2",
    detail="Expected domain/hypothesis fail.",
)
v.record(
    "superlinear dissipation proves BKM integral is finite",
    False,
    computed="no quantitative inequality bounds ||omega||_infty or integrates the BKM norm; the argument is qualitative feedback language",
    claimed="global regularity follows",
    detail="Expected closure fail.",
)
v.record(
    "Xavier-Stokes has no calibrated free parameters",
    False,
    computed="appendix states beta and tau are flow-dependent parameters requiring calibration",
    claimed="geometric framework fixes the regularizing mechanism",
    detail="Expected parameter-status fail.",
)
v.record(
    "numerical verification is reproducible from included code/data",
    False,
    computed="the TeX reports Taylor-Green results but no script, grid data, or convergence study is included",
    claimed="numerical simulations confirm the mechanism",
    detail="Expected reproducibility fail.",
)

sys.exit(v.summary())
