"""Strict input reader and guard classifier for the PF-002 C3 analytical slice.

Virtual lab - simulated experiment tooling, analytical model only. It reads the
reviewed twin under byte, node, depth, duplicate-key, finiteness and NFC limits,
pins the frozen verification block by digest, checks every consumed field before
any arithmetic, and maps each request to exactly one frozen state. No state means
physical support, observation, or the existence of any mechanism.
"""

from decimal import Decimal
from fractions import Fraction
import hashlib
import json
import os
from pathlib import Path
import re
import unicodedata

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-c3-analytical-v1-protocol.json"
FREEZE_DIGEST = "4649adfa77a9f80a75d594a831f82bcaee2656c707ca5ca389cdd72b9481f290"
# Stage 2 pinned the whole twin (3528ee76...). Stage 3 preparation makes the lifecycle explicit:
# every field except these six is pinned by SCIENCE_DIGEST, and the six may take only the two
# states in LIFECYCLE_STATES. So no science field can change, and authority can change only by
# a whole reviewed state.
LIFECYCLE_KEYS = ("execution_authorised", "fixture_verification_authorised", "authorised_modes",
                  "review_state", "stage_3_report_release", "stage_3_review_note")
SCIENCE_DIGEST = "ccee76b0447ae8c1994e261462b28eab64f13c23b83d4e3926065044b9d5484d"
LIFECYCLE_STATES = {
    "fixture": {"execution_authorised": False, "fixture_verification_authorised": True,
                "authorised_modes": ["analytical_verification_fixtures"], "stage_3_report_release": None},
    "report": {"execution_authorised": True, "fixture_verification_authorised": True,
               "authorised_modes": ["analytical_verification_fixtures", "analytical_report"],
               "stage_3_report_release": "commit"},
}
COMMIT = re.compile(r"^[0-9a-f]{40}$")
MAX_NOTE = 600
TOP_LEVEL_KEYS = frozenset((
    "atlas_plan", "authorised_modes", "base_commit", "cases", "claims", "constants", "conventions",
    "diagram", "environment", "evidence_kind", "execution_authorised", "falsification_predicates",
    "fixture_verification_authorised", "frozen_references", "future_plan", "guards", "human_protocol",
    "prohibited_claims", "protocol_revision", "protocol_state", "review_state", "revision_1_commit",
    "revision_2_amendment", "revision_2_amendment_commits", "revision_2_first_commit",
    "revision_2_reason", "revision_3_amendment", "revision_3_first_commit", "revision_3_reason",
    "rivals", "root_approval_commit", "scope", "slice_kind", "source_ledger", "stage_2_review_note",
    "stage_3_report_release", "stage_3_review_note",
    "status", "study", "supported_claims", "variants", "verification_freeze"))
ROOT_APPROVAL = "ea263b4ecdeb7458a58a04f8e3d89066f15222ec"
MAX_INPUT_BYTES = 131072
MAX_INPUT_NODES = 10000
MAX_DEPTH = 12
STATES = ("identity_verified", "identity_failed", "quotient_undefined",
          "outside_regime_unproved", "readout_unknown_unproved", "adverse_not_signal",
          "variant_not_transferable", "refused_input")
RATIONAL = re.compile(r"^-?(0|[1-9][0-9]*)(/[1-9][0-9]*)?$")
MONOMIAL_FACTOR = re.compile(r"^(G|R|s|nu)(\^[1-9])?$")
FROZEN_H = ["-1", "-1/10", "0", "1/10", "1"]
FROZEN_C_Q = ["-1", "0", "1/10", "1", "2"]
FROZEN_LAMBDA = ["G*R*s*nu", "s^2*nu", "R^3", "R*s"]
K1_NULLS = {"all_interaction": "kappa_c_equals_0_or_chi_identically_0",
            "force_only": "b_equals_0_chi0_control_curvature_remains_if_kappa_c_chi0_nonzero"}
K2_NULLS = {"all_C3_effects": "kappa_c_equals_0",
            "partner_part_only": "lambda_Y_equals_0_self_effects_remain"}
VARIANTS = ("C3_original", "O_q", "C3_O", "C3_K1", "C3_K2", "C3_R", "C3_U_q")


class GuardRefusal(ValueError):
    """Input that must never reach arithmetic."""


def _refuse(message):
    raise GuardRefusal(message)


def _no_duplicates(pairs):
    keys = [key for key, _ in pairs]
    if len(keys) != len(set(keys)):
        _refuse("duplicate key")
    return dict(pairs)


def _reject_constant(name):
    _refuse(f"non-finite constant {name}")


def _walk(value, depth, budget):
    budget[0] += 1
    if budget[0] > MAX_INPUT_NODES:
        _refuse("too many nodes")
    if depth > MAX_DEPTH:
        _refuse("too deep")
    if isinstance(value, dict):
        for key, item in value.items():
            if unicodedata.normalize("NFC", key) != key:
                _refuse("non-NFC key")
            _walk(item, depth+1, budget)
    elif isinstance(value, list):
        for item in value:
            _walk(item, depth+1, budget)
    elif isinstance(value, str):
        if unicodedata.normalize("NFC", value) != value:
            _refuse("non-NFC string")
    elif isinstance(value, Decimal):
        if not value.is_finite():
            _refuse("non-finite number")
    elif value is not None and not isinstance(value, (bool, int)):
        _refuse("unsupported value")


def parse_strict(data):
    """Parse bounded bytes. Floats stay Decimal, so quoted digits are kept."""
    if not isinstance(data, bytes):
        _refuse("bytes required")
    if len(data) > MAX_INPUT_BYTES:
        _refuse("input too large")
    try:
        text = data.decode("utf-8")
    except UnicodeDecodeError:
        _refuse("not UTF-8")
    try:
        value = json.loads(text, object_pairs_hook=_no_duplicates, parse_float=Decimal,
                           parse_constant=_reject_constant)
    except GuardRefusal:
        raise
    except (ValueError, RecursionError):
        _refuse("malformed JSON")
    _walk(value, 1, [0])
    return value


def _canonical_digest(value):
    block = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True,
                       allow_nan=False).encode("utf-8")
    return hashlib.sha256(block).hexdigest()


def _plain(data):
    return json.loads(data.decode("utf-8"), object_pairs_hook=_no_duplicates,
                      parse_constant=_reject_constant)


def freeze_digest(data):
    """Digest of the frozen block from standard float parsing, as root defined it."""
    return _canonical_digest(_plain(data)["verification_freeze"])


def science_digest(data):
    """Same canonical form over every field except the six lifecycle keys."""
    plain = _plain(data)
    return _canonical_digest({k: v for k, v in plain.items() if k not in LIFECYCLE_KEYS})


def lifecycle_state(twin):
    """Name the one reviewed lifecycle state the twin is in, or refuse."""
    for key in ("review_state", "stage_3_review_note"):
        value = twin.get(key)
        if not isinstance(value, str) or not 0 < len(value) <= MAX_NOTE:
            _refuse(f"bad lifecycle note {key}")
    for name, state in LIFECYCLE_STATES.items():
        matched = True
        for key, expected in state.items():
            value = twin.get(key)
            if expected == "commit":
                matched = matched and isinstance(value, str) and bool(COMMIT.match(value))
            else:
                matched = matched and type(value) is type(expected) and value == expected
        if matched:
            return name
    _refuse("lifecycle is not a reviewed state")


def read_protocol_bytes(path=None):
    """Only the reviewed twin beside this module may be read."""
    expected = ROOT/PROTOCOL_FILE
    target = expected if path is None else Path(path)
    if os.path.islink(str(target)):
        _refuse("unsafe path")
    if target.resolve() != expected.resolve() or ".." in Path(path or expected).parts:
        _refuse("unsafe path")
    with open(expected, "rb") as stream:
        data = stream.read(MAX_INPUT_BYTES+1)
    return data


def _get(mapping, *keys):
    value = mapping
    for key in keys:
        if not isinstance(value, dict) or key not in value:
            _refuse(f"missing field {'.'.join(keys)}")
        value = value[key]
    return value


def _exact(mapping, keys, expected):
    value = _get(mapping, *keys)
    if type(value) is not type(expected) or value != expected:
        _refuse(f"frozen field changed {'.'.join(keys)}")
    return value


def rational(text):
    if not isinstance(text, str) or not RATIONAL.match(text):
        _refuse("not an exact rational")
    return Fraction(text)


def decimal_field(mapping, *keys):
    value = _get(mapping, *keys)
    if isinstance(value, bool) or not isinstance(value, (Decimal, int)):
        _refuse(f"not a finite number {'.'.join(keys)}")
    return Decimal(value)


def _vertices(raw, symbols):
    if not isinstance(raw, list) or not 2 <= len(raw) <= 8:
        _refuse("bad vertex list")
    out = []
    for pair in raw:
        if not isinstance(pair, list) or len(pair) != 2:
            _refuse("bad vertex")
        out.append(tuple(pair[i] if pair[i] in symbols else rational(pair[i]) for i in range(2)))
    return out


def load_protocol(path=None, data=None):
    """Return the checked twin and its frozen cases, or refuse."""
    if data is None:
        data = read_protocol_bytes(path)
    twin = parse_strict(data)
    if not isinstance(twin, dict) or set(twin) != TOP_LEVEL_KEYS:
        _refuse("unknown or missing top-level field")
    if freeze_digest(data) != FREEZE_DIGEST:
        _refuse("verification freeze changed")
    if science_digest(data) != SCIENCE_DIGEST:
        _refuse("reviewed twin changed outside the lifecycle fields")
    lifecycle = lifecycle_state(twin)
    _exact(twin, ("study",), "pf002-c3-analytical-v1")
    _exact(twin, ("protocol_revision",), 3)
    _exact(twin, ("root_approval_commit",), ROOT_APPROVAL)
    _exact(twin, ("variants", "C3_K1", "null_limits"), K1_NULLS)
    _exact(twin, ("variants", "C3_K2", "null_limits"), K2_NULLS)
    nulls = [case for case in _get(twin, "cases") if case.get("id") == "K-null"]
    if len(nulls) != 1:
        _refuse("K-null case missing")
    freeze = _get(twin, "verification_freeze")
    cases = _get(freeze, "cases")
    _exact(cases, ("h",), FROZEN_H)
    _exact(cases, ("c_and_q",), FROZEN_C_Q)
    _exact(cases, ("gauge_Lambda",), FROZEN_LAMBDA)
    for item in FROZEN_LAMBDA:
        for factor in item.split("*"):
            if not MONOMIAL_FACTOR.match(factor):
                _refuse("bad gauge monomial")
    rectangle = _get(cases, "rectangle_R_nu_micrometre_units")
    _exact(rectangle, ("closed",), True)
    _exact(rectangle, ("R1",), ["1", "0"])
    square = _get(cases, "control_square_s_nu")
    _exact(square, ("closed",), True)
    carriers = _get(cases, "carrier_sets_c_equals_1")
    if not isinstance(carriers, list) or len(carriers) != 3:
        _refuse("carrier set cardinality")
    tolerances = _get(freeze, "tolerances")
    if _get(tolerances, "exact_identities_V1_to_V6_and_V9") != 0:
        _refuse("exact tolerance changed")
    states = _get(freeze, "classifier_states")
    if states != list(STATES):
        _refuse("classifier states changed")
    required = _get(freeze, "required_negative_and_adverse_cases")
    if not isinstance(required, list) or len(required) != 14:
        _refuse("required case cardinality")
    for item in required:
        if set(item) != {"case", "state"} or item["state"] not in STATES:
            _refuse("bad required case")
    return {
        "twin": twin,
        "lifecycle": lifecycle,
        "k_null": nulls[0]["nulls"],
        "h": [rational(x) for x in FROZEN_H],
        "c_q": [rational(x) for x in FROZEN_C_Q],
        "gauge": list(FROZEN_LAMBDA),
        "rectangle": _vertices(_get(rectangle, "vertices"), ("R1",)),
        "rectangle_R1": [rational(x) for x in _get(rectangle, "R1")],
        "rectangle_expected": {k: rational(v) for k, v in _get(rectangle, "expected_at_R1_1").items()},
        "square": _vertices(_get(square, "vertices"), ()),
        "square_expected": rational(_get(square, "expected_B_snu")),
        "square_reversed": rational(_get(square, "reversed")),
        "degenerate_line": rational(_get(square, "degenerate_line_s_fixed_1")),
        "constants": {k: decimal_field(cases, "constants_ieee_double", k)
                      for k in ("F_hat_newtons", "P0_watts", "lambda_metres", "c_metres_per_second",
                                "ell_metres", "Delta_s", "f_hertz", "n_hat")},
        "expected": {k: decimal_field(cases, "constants_expected", k)
                     for k in ("alpha_per_metre_per_unit_h", "alpha_vs_k_n_hat_relative",
                               "Cm_joule_second", "rectangle_Phi_h_radians_per_unit_h",
                               "E_min_joules_per_unit_h", "P_min_watts_per_unit_h")},
        "botermann": {
            "beta": rational(_exact(cases, ("botermann", "beta"), "338/1000")),
            "gamma2_beta2": rational(_exact(cases, ("botermann", "gamma2_beta2_exact"), "28561/221439")),
            "epsilon": decimal_field(cases, "botermann", "epsilon"),
            "sigma": decimal_field(cases, "botermann", "sigma_epsilon_1_sigma"),
            "q_central": decimal_field(cases, "botermann", "expected_q_linear_central"),
            "q_sigma": decimal_field(cases, "botermann", "expected_q_linear_1_sigma")},
        "static_stress": {"Poynting": _exact(cases, ("static_stress", "expected_Poynting"), "0"),
                          "T_zz": _exact(cases, ("static_stress", "expected_T_zz_magnitude"), "eps0*E0^2/2")},
        "carriers": [[(rational(e), rational(p)) for e, p in group] for group in carriers],
        "tolerances": {
            "oracle": decimal_field(tolerances, "V7_checker_vs_oracle_relative"),
            "alpha_kn": decimal_field(tolerances, "alpha_vs_k_n_hat_relative_max"),
            "v8_linear_exact": decimal_field(tolerances, "V8_linear_vs_exact_inversion_relative"),
            "v8_oracle": decimal_field(tolerances, "V8_checker_vs_oracle_relative")},
        "required": [(item["case"], item["state"]) for item in required],
    }


REQUEST_KEYS = {
    "comparison": {"kind", "id", "derived", "oracle", "claimed"},
    "inequality": {"kind", "id", "derived", "oracle"},
    "quotient": {"kind", "h", "A_Rnu", "B_snu", "derived", "oracle", "claimed"},
    "mean_offset": {"kind", "kappa_theta", "Delta", "loading", "readout"},
    "b2_budget": {"kind", "carrier", "incoming_radiation", "variant", "derived", "oracle", "claimed"},
    "transfer": {"kind", "source_variant", "target"},
    "adverse": {"kind", "case"},
    "null": {"kind", "variant", "null", "claimed_scope"},
}
CARRIERS = ("outgoing_free_radiation", "static_stress", "near_field_stress", "background_force")
ADVERSE = ("downstream_reference", "ell_following_skew")


CLAIM_IDS = ("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9")


def _is_terms(value):
    """Polynomial terms: tuple of (name, power) pairs mapped to exact non-boolean numbers."""
    if not isinstance(value, dict):
        return False
    for monomial, coefficient in value.items():
        if not isinstance(monomial, tuple) or not all(
                isinstance(pair, tuple) and len(pair) == 2 and isinstance(pair[0], str)
                and type(pair[1]) is int and pair[1] > 0 for pair in monomial):
            return False
        if isinstance(coefficient, bool) or not isinstance(coefficient, (Fraction, int)):
            return False
    return True


def _value_kind(value):
    """Supported scientific payloads only. Booleans, labels and None are never values."""
    if isinstance(value, bool) or value is None:
        return None
    if isinstance(value, Fraction):
        return "rational"
    if isinstance(value, Decimal):
        return "decimal" if value.is_finite() else None
    if _is_terms(value):
        return "polynomial"
    if isinstance(value, tuple) and len(value) == 2 and all(_is_terms(v) for v in value):
        return "polynomial_pair"
    return None


value_kind = _value_kind


def _compare(request):
    derived, oracle, claimed = request["derived"], request["oracle"], request["claimed"]
    kinds = {_value_kind(derived), _value_kind(oracle), _value_kind(claimed)}
    if None in kinds or len(kinds) != 1:
        return "refused_input"
    return "identity_verified" if derived == oracle == claimed else "identity_failed"


def _inequality(request):
    """Exact margin that must be non-negative, from two independent derivations."""
    derived, oracle = request["derived"], request["oracle"]
    if _value_kind(derived) != "rational" or _value_kind(oracle) != "rational":
        return "refused_input"
    return "identity_verified" if derived == oracle and derived >= 0 else "identity_failed"


def classify(request):
    """Map one request to exactly one frozen state. Never a physical verdict."""
    if not isinstance(request, dict) or request.get("kind") not in REQUEST_KEYS:
        return "refused_input"
    if set(request) != REQUEST_KEYS[request["kind"]]:
        return "refused_input"
    kind = request["kind"]
    if kind == "comparison":
        return _compare(request) if request["id"] in CLAIM_IDS else "refused_input"
    if kind == "inequality":
        return _inequality(request) if request["id"] == "V9" else "refused_input"
    if kind == "quotient":
        values = (request["h"], request["A_Rnu"], request["B_snu"])
        if not all(isinstance(v, Fraction) for v in values):
            return "refused_input"
        # Guard first: no 0/0 is ever formed or compared.
        return "quotient_undefined" if 0 in values else _compare(request)
    if kind == "mean_offset":
        kappa, delta = request["kappa_theta"], request["Delta"]
        if not isinstance(kappa, Fraction) or not isinstance(delta, Fraction) or kappa < 0:
            return "refused_input"
        if request["loading"] not in ("constant", "phi_dependent") or request["readout"] not in ("unknown", "declared"):
            return "refused_input"
        if kappa == 0 or delta != 0 or request["loading"] != "constant":
            return "outside_regime_unproved"
        # The freeze declares no detector transfer, so no measured value is ever proved here.
        return "readout_unknown_unproved"
    if kind == "b2_budget":
        if request["carrier"] not in CARRIERS or request["variant"] not in VARIANTS:
            return "refused_input"
        if not isinstance(request["incoming_radiation"], bool):
            return "refused_input"
        if (request["carrier"] != "outgoing_free_radiation" or request["incoming_radiation"]
                or request["variant"] in ("C3_K1", "C3_K2")):
            return "outside_regime_unproved"
        # In class, only the budget arithmetic can be verified, never the channel.
        return _compare(request)
    if kind == "transfer":
        if request["source_variant"] not in VARIANTS + ("Botermann",) or request["target"] not in VARIANTS:
            return "refused_input"
        if request["target"] == "C3_original" and request["source_variant"] != "C3_original":
            return "variant_not_transferable"
        return "refused_input"
    if kind == "adverse":
        return "adverse_not_signal" if request["case"] in ADVERSE else "refused_input"
    variant, null, scope = request["variant"], request["null"], request["claimed_scope"]
    if variant == "C3_K1":
        truth = {"kappa_c_equals_0": "all_interaction", "chi_identically_0": "all_interaction",
                 "b_equals_0": "force_only"}
    elif variant == "C3_K2":
        truth = {"kappa_c_equals_0": "all_C3_effects", "lambda_Y_equals_0": "partner_part_only"}
    elif variant in ("C3_original", "O_q", "C3_O", "C3_R"):
        truth = {"h_equals_0": "all"}
    elif variant == "C3_U_q":
        truth = {"q_equals_0": "all"}
    else:
        return "refused_input"
    if null not in truth:
        return "refused_input"
    return "identity_verified" if truth[null] == scope else "identity_failed"
