from __future__ import annotations

import datetime
import json
import math
from pathlib import Path
from typing import Any

import numpy as np
import yaml
from scipy.integrate import quad

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "results" / "answf_eft" / "result.json"
SPEC = ROOT / "research" / "answf" / "ANSWF_EFT_POSITIVITY_SPEC.md"
SWF_RESULT = ROOT / "results" / "swf_ism_foundation" / "result.json"
WILSONS = ROOT / "datasets" / "positivity_wilsons.yaml"

ABS_TOL = 1.0e-11
COPOS_TOL = 2.0e-6


def utc_now_z() -> str:
    return datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds").replace("+00:00", "Z")


def synthetic_im_amplitude(s: float, threshold: float, scale: float, strength: float) -> float:
    if s <= threshold:
        return 0.0
    phase = math.sqrt(max(0.0, 1.0 - threshold / s))
    return strength * s * phase * math.exp(-(s - threshold) / scale)


def dispersion_curvature(threshold: float, scale: float, direct_strength: float, crossed_strength: float) -> tuple[float, float]:
    def integrand(s: float) -> float:
        direct = synthetic_im_amplitude(s, threshold, scale, direct_strength)
        crossed = synthetic_im_amplitude(s, threshold, scale * 1.15, crossed_strength)
        return (direct + crossed) / (s ** 3)

    val, err = quad(integrand, threshold, np.inf, epsabs=1e-12, epsrel=1e-11, limit=300)
    return (2.0 / math.pi) * val, (2.0 / math.pi) * err


def scalar_forward_curvature(c4: float, lam: float = 1.0) -> float:
    # A_fwd = (4 c4 / Lambda^4) s^2 -> d^2 A/ds^2 = 8 c4/Lambda^4.
    return 8.0 * c4 / (lam ** 4)


def mixed_form(theta: np.ndarray, a: float, b: float, c: float) -> np.ndarray:
    cc = np.cos(theta) ** 2
    ss = np.sin(theta) ** 2
    return a * cc ** 2 + b * ss ** 2 + 2.0 * c * cc * ss


def copositivity_probe(a: float, b: float, c: float) -> dict[str, Any]:
    analytic = bool(a >= 0.0 and b >= 0.0 and c + math.sqrt(max(a * b, 0.0)) >= -ABS_TOL)
    theta = np.linspace(0.0, 0.5 * math.pi, 20001)
    vals = mixed_form(theta, a, b, c)
    min_val = float(np.min(vals))
    numeric = bool(min_val >= -COPOS_TOL)
    return {
        "A": a,
        "B": b,
        "C": c,
        "C_plus_sqrt_AB": c + math.sqrt(max(a * b, 0.0)),
        "analytic_copositive": analytic,
        "numeric_min_over_theta": min_val,
        "numeric_nonnegative": numeric,
        "analytic_numeric_agree": analytic == numeric,
    }


def gravity_pole_subtraction_probe() -> dict[str, Any]:
    # Algebraic implementation probe for A_hat = A_total + 8*pi*G*s^2/t.
    # Values are dimensionless test numbers, not physical G or a physical amplitude.
    gtest = 0.013
    c4 = 0.021
    svals = np.array([-0.4, -0.2, 0.0, 0.2, 0.4], dtype=float)
    expected = 4.0 * c4 * svals ** 2
    residuals = []
    curvature_residuals = []
    for t in (1e-1, 1e-2, 1e-3, 1e-4):
        pole = -8.0 * math.pi * gtest * svals ** 2 / t
        total = expected + pole
        subtracted = total + 8.0 * math.pi * gtest * svals ** 2 / t
        residuals.append(float(np.max(np.abs(subtracted - expected))))
        # All are quadratic in s, so fit curvature after subtraction.
        coef = np.polyfit(svals, subtracted, 2)
        recovered_d2 = 2.0 * coef[0]
        curvature_residuals.append(abs(recovered_d2 - scalar_forward_curvature(c4)))
    return {
        "max_amplitude_subtraction_residual": max(residuals),
        "max_curvature_residual": max(curvature_residuals),
        "pass": bool(max(residuals) <= 5e-12 and max(curvature_residuals) <= 5e-11),
    }


def load_wilson_config() -> dict[str, float]:
    obj = yaml.safe_load(WILSONS.read_text(encoding="utf-8"))
    operators = obj.get("operators", {})
    return {str(k): float(v) for k, v in operators.items()}


def main() -> None:
    swf_status = "MISSING"
    swf_pass = False
    if SWF_RESULT.exists():
        obj = json.loads(SWF_RESULT.read_text(encoding="utf-8"))
        swf_status = str(obj.get("status", "UNKNOWN"))
        swf_pass = bool(obj.get("verdict") == "PASS" and swf_status == "PASS_SWF_ISM_INFORMATION_STATE_FOUNDATION_TO_ANSWF_HANDOFF")

    interacting_curv, interacting_err = dispersion_curvature(1.0, 2.0, 0.7, 0.5)
    free_curv, free_err = dispersion_curvature(1.0, 2.0, 0.0, 0.0)

    c4_probes = [-0.02, 0.0, 0.01, 0.15]
    scalar_probes = [
        {
            "c4": c4,
            "forward_curvature": scalar_forward_curvature(c4),
            "sign_matches": bool((c4 > 0) == (scalar_forward_curvature(c4) > 0)),
        }
        for c4 in c4_probes
    ]

    mixed_cases = [
        (1.0, 1.0, 0.25),
        (1.0, 4.0, -1.9),
        (1.0, 4.0, -2.1),
        (0.3, 2.7, -0.85),
        (0.3, 2.7, -0.95),
    ]
    mixed = [copositivity_probe(*case) for case in mixed_cases]
    gravity = gravity_pole_subtraction_probe()
    wilsons = load_wilson_config()

    checks = {
        "swf_ism_handoff_passes": swf_pass,
        "interacting_positive_spectral_density_gives_positive_curvature": bool(interacting_curv > interacting_err >= 0.0),
        "zero_spectral_density_gives_zero_not_strict_positive": bool(abs(free_curv) <= ABS_TOL and free_err <= ABS_TOL),
        "single_scalar_curvature_sign_tracks_c4": all(p["sign_matches"] for p in scalar_probes),
        "single_scalar_positive_c4_is_strictly_positive": bool(all(p["forward_curvature"] > 0.0 for p in scalar_probes if p["c4"] > 0.0)),
        "mixed_copositivity_formula_matches_angular_scan": all(p["analytic_numeric_agree"] for p in mixed),
        "gravity_pole_subtraction_recovers_regular_amplitude": bool(gravity["pass"]),
        "configured_wilson_values_finite": bool(all(math.isfinite(v) for v in wilsons.values())),
        "configured_wilson_values_positive": bool(all(v > 0.0 for v in wilsons.values())),
        "configured_scalar_phi4_margin_positive": bool(wilsons.get("c_phi4", float("nan")) > 0.0),
    }

    claim_guards = {
        "s_matrix_axioms_are_assumptions_not_derived_by_answf": True,
        "strict_positivity_is_conditional_on_nonzero_absorptive_strength": True,
        "gravity_safe_statement_requires_fixed_nonzero_t_or_known_pole_subtraction": True,
        "synthetic_dispersion_density_is_consistency_probe_not_measured_cross_section": True,
        "mixed_copositivity_probe_validates_math_not_full_wilson_tensor_mapping": True,
        "configured_positive_wilsons_are_bundle_inputs_not_predictions_derived_here": True,
        "sanswf_gauge_bfb_unitarity_layer_not_claimed_here": True,
        "historical_rows_not_renumbered": True,
    }

    verdict = "PASS" if all(checks.values()) and all(claim_guards.values()) else "FAIL"
    status = "PASS_ANSWF_EFT_POSITIVITY_TO_SANSWF_HANDOFF" if verdict == "PASS" else "FAIL_ANSWF_EFT_POSITIVITY"

    result = {
        "row": 0.2,
        "stage": "ANSWF",
        "gate": "answf_eft_positivity",
        "signature": "ANSWF_EFT_POSITIVITY_PREFLIGHT_v1",
        "context": "LIVE",
        "tier": "Critical",
        "blocking": True,
        "timestamp_utc": utc_now_z(),
        "verdict": verdict,
        "status": status,
        "upstream_dependency": {
            "required": "PASS_SWF_ISM_INFORMATION_STATE_FOUNDATION_TO_ANSWF_HANDOFF",
            "observed": swf_status,
            "pass": swf_pass,
        },
        "checks": checks,
        "claim_guards": claim_guards,
        "metrics": {
            "dispersion_probe": {
                "interacting_curvature": interacting_curv,
                "interacting_quad_error": interacting_err,
                "free_curvature": free_curv,
                "free_quad_error": free_err,
            },
            "single_scalar_probes": scalar_probes,
            "mixed_copositivity_probes": mixed,
            "gravity_safe_probe": gravity,
            "configured_wilson_inputs": wilsons,
        },
        "handoff": {
            "from": "ANSWF EFT amplitudes satisfying declared forward positivity/admissibility conditions",
            "to": "SANSWF gauge/symmetry, bounded-from-below, and perturbative-unitarity layer",
            "downstream_rows_renumbered": False,
        },
        "open_boundaries": [
            "ANSWF does not prove analyticity, crossing, unitarity, or polynomial boundedness from deeper UTFANSWF axioms; the dispersion conclusions are conditional on those standard S-matrix assumptions.",
            "The synthetic spectral functions validate the sign logic but are not physical cross-section data.",
            "The mixed two-field scan validates the copositivity criterion but does not instantiate every spin/flavor Wilson tensor in the full theory.",
            "Gauge covariance, scalar-potential BFB, anomaly cancellation, and partial-wave unitarity remain downstream SANSWF tasks.",
        ],
        "specification": str(SPEC.relative_to(ROOT)),
        "notes": "Critical EFT-admissibility preflight. Execution label 0.2 preserves historical row numbering.",
    }

    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
    print(json.dumps({"row": 0.2, "stage": "ANSWF", "verdict": verdict, "status": status}, indent=2))
    if verdict != "PASS":
        raise SystemExit(1)


if __name__ == "__main__":
    main()
