"""Fail-closed local contact/counterterm manifest for Apeiron AP1-R3.

The manifest records the second-variation slots required by the frozen CTP
contract.  It does not evaluate a physical response kernel and it deliberately
keeps any coefficient or functional not fixed by the allowed authorities on a
documentary hold.
"""
from __future__ import annotations

from hashlib import sha256
import json
from pathlib import Path


class LocalVariationManifestError(RuntimeError):
    """The local variation contract is incomplete or overclaims readiness."""


REQUIRED_COUNTERTERM_FAMILIES = (
    "cosmological",
    "einstein_hilbert",
    "portal_mass_c_m",
    "curvature_R2",
    "curvature_Ricci2",
    "boundary_box_R",
    "euler_density",
)

REQUIRED_PORTAL_CONTACTS = (
    ("sigma_portal", "sigma"),
    ("sigma_portal", "theta"),
    ("theta_portal", "sigma"),
    ("theta_portal", "theta"),
)


def file_sha256(path: Path) -> str:
    digest = sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _require_markers(text: str, markers: tuple[str, ...], label: str) -> None:
    missing = [marker for marker in markers if marker not in text]
    if missing:
        raise LocalVariationManifestError(f"{label} missing markers: {missing}")


def _contact_terms() -> list[dict]:
    common = {
        "support": "covariant_delta_4(x,x_prime)",
        "assembly_stage": "before_coupled_linearized_Ward_test",
        "free_parameter_added": False,
    }
    return [
        {
            **common,
            "id": "C_T_G",
            "row_source": "metric_stress",
            "column_perturbation": "metric",
            "origin": "explicit_metric_variation_of_T_chi",
            "functional_form": "delta_explicit<T_chi_mu_nu>_ren/delta_g_rho_sigma",
            "status": "FORM_REGISTERED_COMPONENT_PROJECTION_BLOCKED",
        },
        {
            **common,
            "id": "C_T_SIGMA",
            "row_source": "metric_stress",
            "column_perturbation": "sigma",
            "origin": "explicit_portal_mass_dependence_of_T_chi",
            "functional_form": "-1/2 g_mu_nu m_chi2_,sigma <chi2>_ren delta4 (up_to_the_single_CTP_sign_convention)",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
        {
            **common,
            "id": "C_T_THETA",
            "row_source": "metric_stress",
            "column_perturbation": "theta",
            "origin": "explicit_portal_mass_dependence_of_T_chi",
            "functional_form": "-1/2 g_mu_nu m_chi2_,theta <chi2>_ren delta4 (up_to_the_single_CTP_sign_convention)",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
        {
            **common,
            "id": "C_SIGMA_G",
            "row_source": "sigma_portal",
            "column_perturbation": "metric",
            "origin": "metric_and_density_variation_of_-1/2_m_chi2_,sigma_chi2",
            "functional_form": "delta[-1/2 sqrt(-g) m_chi2_,sigma chi2]/delta_g_rho_sigma",
            "status": "FORM_REGISTERED_COMPONENT_PROJECTION_BLOCKED",
        },
        {
            **common,
            "id": "C_THETA_G",
            "row_source": "theta_portal",
            "column_perturbation": "metric",
            "origin": "metric_and_density_variation_of_-1/2_m_chi2_,theta_chi2",
            "functional_form": "delta[-1/2 sqrt(-g) m_chi2_,theta chi2]/delta_g_rho_sigma",
            "status": "FORM_REGISTERED_COMPONENT_PROJECTION_BLOCKED",
        },
        {
            **common,
            "id": "C_SIGMA_SIGMA",
            "row_source": "sigma_portal",
            "column_perturbation": "sigma",
            "origin": "portal_mass_Hessian",
            "functional_form": "-1/2 m_chi2_,sigma_sigma <chi2>_ren delta4",
            "mass_derivative": "4 lambda cos(2 theta/f_phase)",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
        {
            **common,
            "id": "C_SIGMA_THETA",
            "row_source": "sigma_portal",
            "column_perturbation": "theta",
            "origin": "portal_mass_Hessian",
            "functional_form": "-1/2 m_chi2_,sigma_theta <chi2>_ren delta4",
            "mass_derivative": "-8 lambda (v+sigma) sin(2 theta/f_phase)/f_phase",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
        {
            **common,
            "id": "C_THETA_SIGMA",
            "row_source": "theta_portal",
            "column_perturbation": "sigma",
            "origin": "portal_mass_Hessian",
            "functional_form": "-1/2 m_chi2_,theta_sigma <chi2>_ren delta4",
            "mass_derivative": "-8 lambda (v+sigma) sin(2 theta/f_phase)/f_phase",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
        {
            **common,
            "id": "C_THETA_THETA",
            "row_source": "theta_portal",
            "column_perturbation": "theta",
            "origin": "portal_mass_Hessian",
            "functional_form": "-1/2 m_chi2_,theta_theta <chi2>_ren delta4",
            "mass_derivative": "-8 lambda (v+sigma)^2 cos(2 theta/f_phase)/f_phase^2",
            "status": "ANALYTIC_FORM_REGISTERED_PHYSICAL_BACKGROUND_BLOCKED",
        },
    ]


def _counterterm_variations(cm_anchor_sha256: str) -> list[dict]:
    common = {
        "support": "local_covariant_distribution",
        "assembly_stage": "with_contacts_before_coupled_linearized_Ward_test",
        "state_dependent_UV_coefficient_allowed": False,
        "coefficient_value_supplied_here": False,
        "free_parameter_added": False,
    }
    return [
        {
            **common,
            "id": "CT_LAMBDA_GG",
            "family": "cosmological",
            "affected_blocks": ["metric_stress<-metric"],
            "action_anchor": "delta^2 Integral sqrt(-g) delta_Lambda / delta_g delta_g",
            "status": "VARIATION_SLOT_REGISTERED_COEFFICIENT_FROM_FROZEN_RENORMALIZATION_ONLY",
        },
        {
            **common,
            "id": "CT_EH_GG",
            "family": "einstein_hilbert",
            "affected_blocks": ["metric_stress<-metric"],
            "action_anchor": "delta^2 Integral sqrt(-g) (delta_M2/2) R / delta_g delta_g",
            "double_count_guard": "renormalized_Planck_mass_entered_once",
            "status": "VARIATION_SLOT_REGISTERED_COEFFICIENT_FROM_FROZEN_RENORMALIZATION_ONLY",
        },
        {
            **common,
            "id": "CT_CM_ALL",
            "family": "portal_mass_c_m",
            "affected_blocks": [
                "metric_stress<-metric",
                "metric_stress<-sigma",
                "metric_stress<-theta",
                "sigma_portal<-metric",
                "sigma_portal<-sigma",
                "sigma_portal<-theta",
                "theta_portal<-metric",
                "theta_portal<-sigma",
                "theta_portal<-theta",
            ],
            "action_anchor": "S_ct,c_m = Integral d4x sqrt(-g) [+ C_chi2/2 * m_chi^2(sigma,theta)]",
            "coefficient_anchor": "C_chi2 from the hash-bound canonical flat-slice renormalization",
            "anchor_artifact_sha256": cm_anchor_sha256,
            "status": "ACTION_FUNCTIONAL_ANCHORED_PHYSICAL_BACKGROUND_STILL_BLOCKED",
        },
        {
            **common,
            "id": "CT_R2_GG",
            "family": "curvature_R2",
            "affected_blocks": ["metric_stress<-metric"],
            "action_anchor": "delta^2 Integral sqrt(-g) c_R2 R^2 / delta_g delta_g",
            "status": "VARIATION_SLOT_REGISTERED_COEFFICIENT_FROM_FROZEN_RENORMALIZATION_ONLY",
        },
        {
            **common,
            "id": "CT_RICCI2_GG",
            "family": "curvature_Ricci2",
            "affected_blocks": ["metric_stress<-metric"],
            "action_anchor": "delta^2 Integral sqrt(-g) c_Ricci2 R_mu_nu R^mu_nu / delta_g delta_g",
            "status": "VARIATION_SLOT_REGISTERED_COEFFICIENT_FROM_FROZEN_RENORMALIZATION_ONLY",
        },
        {
            **common,
            "id": "CT_BOX_R_BOUNDARY",
            "family": "boundary_box_R",
            "affected_blocks": ["boundary_and_initial_surface_only"],
            "action_anchor": "delta^2 Integral sqrt(-g) c_boxR Box R / delta_g delta_g",
            "bulk_rule": "never_drop_until_boundary_and_initial_surface_convention_is_fixed",
            "status": "REDUNDANCY_REGISTERED_BOUNDARY_CONVENTION_BLOCKED",
        },
        {
            **common,
            "id": "CT_EULER_GG",
            "family": "euler_density",
            "affected_blocks": ["metric_stress<-metric", "boundary_bookkeeping"],
            "action_anchor": "delta^2 Integral sqrt(-g) c_E Euler_4 / delta_g delta_g",
            "bulk_rule": "four_dimensional_topological_redundancy_retained_for_regulator_bookkeeping",
            "status": "REDUNDANCY_REGISTERED_BOUNDARY_CONVENTION_BLOCKED",
        },
    ]


def validate_manifest(manifest: dict) -> dict:
    if manifest.get("physical_kernel_ready") is not False:
        raise LocalVariationManifestError("manifest must not release the physical kernel")
    if manifest.get("initial_state_variation", {}).get("separate_from_local_manifest") is not True:
        raise LocalVariationManifestError("initial-state variation must remain separate")

    contacts = manifest.get("local_contact_variations", [])
    counterterms = manifest.get("local_counterterm_variations", [])
    identifiers = [entry.get("id") for entry in contacts + counterterms]
    if any(not item for item in identifiers) or len(identifiers) != len(set(identifiers)):
        raise LocalVariationManifestError("variation identifiers must be non-empty and unique")

    portal_pairs = {
        (entry.get("row_source"), entry.get("column_perturbation"))
        for entry in contacts
        if entry.get("origin") == "portal_mass_Hessian"
    }
    missing_pairs = sorted(set(REQUIRED_PORTAL_CONTACTS) - portal_pairs)
    if missing_pairs:
        raise LocalVariationManifestError(f"portal Hessian coverage incomplete: {missing_pairs}")

    families = {entry.get("family") for entry in counterterms}
    missing_families = sorted(set(REQUIRED_COUNTERTERM_FAMILIES) - families)
    if missing_families:
        raise LocalVariationManifestError(f"counterterm families missing: {missing_families}")

    if any(entry.get("state_dependent_UV_coefficient_allowed") is not False for entry in counterterms):
        raise LocalVariationManifestError("state-dependent UV counterterms are forbidden")
    if any(entry.get("coefficient_value_supplied_here") is not False for entry in counterterms):
        raise LocalVariationManifestError("this structural manifest may not invent coefficients")

    cm_entries = [entry for entry in counterterms if entry.get("family") == "portal_mass_c_m"]
    if (
        len(cm_entries) != 1
        or cm_entries[0].get("status")
        != "ACTION_FUNCTIONAL_ANCHORED_PHYSICAL_BACKGROUND_STILL_BLOCKED"
        or not cm_entries[0].get("anchor_artifact_sha256")
    ):
        raise LocalVariationManifestError("c_m functional must be bound to the validated action anchor")

    return {
        "status": "PASS_FAIL_CLOSED",
        "contact_entries": len(contacts),
        "counterterm_entries": len(counterterms),
        "portal_Hessian_matrix_complete": True,
        "all_required_counterterm_families_registered": True,
        "state_dependent_UV_counterterms_absent": True,
        "invented_counterterm_coefficients_absent": True,
        "c_m_action_anchor_enforced": True,
        "c_m_documentary_hold_enforced": False,
        "physical_kernel_ready": False,
    }


def build_manifest(
    response_spec: Path,
    a3_requirements: Path,
    canonical_spec: Path,
    cm_anchor: Path,
) -> dict:
    response_text = response_spec.read_text(encoding="utf-8")
    a3_text = a3_requirements.read_text(encoding="utf-8")
    canonical_text = canonical_spec.read_text(encoding="utf-8")
    _require_markers(
        response_text,
        ("Pi_AB,contact", "Pi_AB,ct", "delta J_A,state", "erst vollständige Stress-/Portalantwort, dann Ward-Prüfung"),
        "response specification",
    )
    _require_markers(
        a3_text,
        ("δΛ", "δM²", "c_m", "R²", "R_μνR^μν", "keine zustandsabhängigen UV-Gegenparameter"),
        "A3 requirements",
    )
    _require_markers(
        canonical_text,
        ("m_χ²(σ,θ)", "Four Pauli–Villars sectors", "finite R² coefficient is zero"),
        "canonical specification",
    )
    anchor = json.loads(cm_anchor.read_text(encoding="utf-8"))
    if (
        anchor.get("classification")
        != "EXACT_CM_ACTION_ANCHOR_PASS_PHYSICAL_KERNEL_STILL_BLOCKED"
        or anchor.get("validation", {}).get("all_pass") is not True
        or anchor.get("physical_kernel_ready") is not False
        or anchor.get("exact_action_anchor", {}).get("free_parameter_added") is not False
    ):
        raise LocalVariationManifestError("c_m action anchor is missing, invalid, or overclaims readiness")
    expected_action = (
        "S_ct,c_m = Integral d4x sqrt(-g) [+ C_chi2/2 * m_chi^2(sigma,theta)]"
    )
    if anchor.get("exact_action_anchor", {}).get("action") != expected_action:
        raise LocalVariationManifestError("c_m action anchor functional mismatch")
    cm_anchor_sha256 = file_sha256(cm_anchor)

    manifest = {
        "schema": "apeiron-ap1-r3-local-variation-manifest-v1.1",
        "classification": "LOCAL_VARIATION_MANIFEST_COMPLETE_CM_ANCHORED_FAIL_CLOSED_PHYSICAL_EVALUATION_BLOCKED",
        "authority_sha256": {
            "response_spec": file_sha256(response_spec),
            "a3_requirements": file_sha256(a3_requirements),
            "canonical_homogeneous_spec": file_sha256(canonical_spec),
            "cm_counterterm_action_anchor": cm_anchor_sha256,
        },
        "source_order": ["metric_stress", "sigma_portal", "theta_portal"],
        "single_CTP_variation_convention_required": True,
        "local_contact_variations": _contact_terms(),
        "local_counterterm_variations": _counterterm_variations(cm_anchor_sha256),
        "initial_state_variation": {
            "separate_from_local_manifest": True,
            "assembly_stage": "after_kernel_and_local_terms_as_a_separately_labeled_source",
            "UV_counterterm_role": "none",
        },
        "mandatory_assembly_order": [
            "nonlocal_retarded_commutator_blocks",
            "local_contact_variations",
            "local_counterterm_variations",
            "separate_initial_state_variation",
            "coupled_linearized_Ward_test",
            "scalar_constraint_elimination",
        ],
        "physical_kernel_ready": False,
        "blocked_before_physical_evaluation": [
            "new_AP1_M1_background",
            "component_and_gauge_invariant_scalar_projection",
            "pilot_derived_physical_tolerances_frozen_in_advance",
        ],
        "claim_boundary": "structural local-variation routing only; no evaluated physical contact term, counterterm kernel, Ward result, observable, fit or significance",
    }
    manifest["validation"] = validate_manifest(manifest)
    return manifest


def main() -> None:
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("response_spec", type=Path)
    parser.add_argument("a3_requirements", type=Path)
    parser.add_argument("canonical_spec", type=Path)
    parser.add_argument("cm_anchor", type=Path)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    manifest = build_manifest(
        args.response_spec, args.a3_requirements, args.canonical_spec, args.cm_anchor
    )
    rendered = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
    if args.output is None:
        print(rendered, end="")
    else:
        args.output.write_text(rendered, encoding="utf-8")


if __name__ == "__main__":
    main()
