"""Frozen nominal checker for PF-002 C3-S M1. Stdlib only.

The library implements the reviewed nominal algebra. Its command line is
disabled: it refuses with `launch_disabled` before any scientific
calculation or result creation, because execution_authorised is false.
"""

import json
import math
import unicodedata

PROTOCOL_BYTES_MAX = 16384
S_ABS_TOL = 5e-12
AREA_REL_TOL = 1e-12

TOP_KEYS = {
    "protocol_id", "state", "execution_authorised",
    "fixture_verification_authorised", "authorised_modes", "scope", "inputs",
    "arms", "integrals", "quantities", "quantity_states", "refusal_reasons",
    "instrument_unproved_reasons", "sideband", "limits",
    "standing_limitations",
}


class Refusal(Exception):
    def __init__(self, reason):
        super().__init__(reason)
        self.reason = reason


def _reject_duplicates(pairs):
    out = {}
    for key, value in pairs:
        if not isinstance(key, str) or unicodedata.normalize("NFC", key) != key:
            raise Refusal("input_invalid")
        if key in out:
            raise Refusal("input_invalid")
        out[key] = value
    return out


def _check_nfc(value):
    if isinstance(value, str):
        if unicodedata.normalize("NFC", value) != value:
            raise Refusal("input_invalid")
    elif isinstance(value, dict):
        for item in value.values():
            _check_nfc(item)
    elif isinstance(value, list):
        for item in value:
            _check_nfc(item)


def _finite(value):
    if isinstance(value, bool):
        return
    if isinstance(value, (int, float)):
        if not math.isfinite(float(value)):
            raise Refusal("input_invalid")
    elif isinstance(value, dict):
        for item in value.values():
            _finite(item)
    elif isinstance(value, list):
        for item in value:
            _finite(item)


def _depth_nodes(value, depth=1):
    if depth > 6:
        raise Refusal("input_invalid")
    if isinstance(value, dict):
        return 1 + sum(_depth_nodes(item, depth + 1) for item in value.values())
    if isinstance(value, list):
        return 1 + sum(_depth_nodes(item, depth + 1) for item in value)
    return 1


def _bad_constant(name):
    raise Refusal("input_invalid")


def _finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise Refusal("input_invalid")
    return value


EXPECTED_SCOPE = {
    "window": "drive_free", "collection": "aligned_u_e1",
    "total_damping": "kappa_I", "axial_carrier_directions": "matched_signed",
    "chart": "n_gt_abs_m", "chibar": "chi0+(b_bg+sigma*b_P)*X",
}
EXPECTED_INPUTS = {
    "signed": ["eta", "b_P", "b_bg", "chi0"],
    "positive": ["n0", "DX", "L", "hbar"], "kappa_min": 0.0,
    "kappaT_max": 0.1,
    "preparation": {"m0": 0.0, "phi0": "-pi/2", "nu0": 1.0},
}
EXPECTED_ARMS = {
    "orientations": ["+", "-"], "mirrors": ["+", "-"], "leg_count": 4,
    "reverse_definitions": {
        "Delta_minus(t)": "-Delta_plus(T-t)", "X_minus(t)": "X_plus(T-t)",
        "decay_clock": "forward_fresh_preparation",
    },
}
EXPECTED_INTEGRALS = {
    "route_a": "real_antiderivative",
    "route_b": "dimensionless_complex_plus_piecewise_arms",
    "normalised_kappaL": [0.01, 0.025, 0.0],
    "S_absolute_tolerance": S_ABS_TOL,
    "area_relative_tolerance": AREA_REL_TOL,
    "difference_evaluation": "-expm1(-y)",
}
EXPECTED_LIMITS = {
    "protocol_bytes_max": PROTOCOL_BYTES_MAX, "record_bytes_max": 65536,
    "record_nodes_max": 2000, "stream_bytes_max": 65536,
    "run_seconds_max_including_cleanup": 60, "workers": 1, "retries": 0,
}
EXPECTED_SIDEBAND = {"bound_formula": "(hbar/c)*(B+omega0*delta_d)*N_tot",
                     "counts": "total_not_net"}


def parse_protocol(data):
    if not isinstance(data, (bytes, bytearray)) or len(data) > PROTOCOL_BYTES_MAX:
        raise Refusal("input_invalid")
    try:
        text = bytes(data).decode("utf-8")
    except UnicodeDecodeError:
        raise Refusal("input_invalid")
    if unicodedata.normalize("NFC", text) != text:
        raise Refusal("input_invalid")
    try:
        proto = json.loads(text, object_pairs_hook=_reject_duplicates,
                           parse_constant=_bad_constant, parse_float=_finite_float)
    except Refusal:
        raise
    except Exception:
        raise Refusal("input_invalid")
    _check_nfc(proto)
    _finite(proto)
    if _depth_nodes(proto) > 500:
        raise Refusal("input_invalid")
    if not isinstance(proto, dict) or set(proto) != TOP_KEYS:
        raise Refusal("input_invalid")
    if proto["protocol_id"] != "pf002-c3s-m1-nominal-v1" or proto["state"] != "proposed":
        raise Refusal("input_invalid")
    if proto["execution_authorised"] is not False:
        raise Refusal("input_invalid")
    if proto["fixture_verification_authorised"] is not False:
        raise Refusal("input_invalid")
    if proto["authorised_modes"] != []:
        raise Refusal("input_invalid")
    if proto["scope"] != EXPECTED_SCOPE or proto["inputs"] != EXPECTED_INPUTS:
        raise Refusal("input_invalid")
    if proto["arms"] != EXPECTED_ARMS or proto["integrals"] != EXPECTED_INTEGRALS:
        raise Refusal("input_invalid")
    if proto["limits"] != EXPECTED_LIMITS or proto["sideband"] != EXPECTED_SIDEBAND:
        raise Refusal("input_invalid")
    if proto["quantities"] != QUANTITY_IDS:
        raise Refusal("input_invalid")
    if proto["quantity_states"] != ["nominal_verified", "nominal_refused",
                                     "instrument_unproved"]:
        raise Refusal("input_invalid")
    return proto


QUANTITY_IDS = [
    "S1", "S2", "A_n_plus", "A_n_minus", "A_n2_plus", "A_n2_minus",
    "DeltaPsi_plus", "DeltaPsi_minus", "DeltaJ_plus", "DeltaJ_minus",
    "closure_plus", "closure_minus", "fixed_stage_A_n2", "no_lobe_A_n",
    "no_lobe_A_n2", "eps_max", "force_residual_bound", "sideband_impulse_bound",
]


def load_protocol(path):
    with open(path, "rb") as stream:
        data = stream.read(PROTOCOL_BYTES_MAX + 1)
    return parse_protocol(data)


def _positive(name, value):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise Refusal("input_invalid")
    value = float(value)
    if not math.isfinite(value) or value <= 0.0 or value > 1e100:
        raise Refusal("input_invalid")
    return value


def _nonnegative(name, value):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise Refusal("input_invalid")
    value = float(value)
    if not math.isfinite(value) or value < 0.0 or value > 1e100:
        raise Refusal("input_invalid")
    return value


def require_finite(value, reason="input_invalid"):
    if isinstance(value, bool) or not isinstance(value, (int, float)) \
            or not math.isfinite(float(value)):
        raise Refusal(reason)
    return float(value)


def one_minus_exp_neg(y):
    """Stable 1-exp(-y) for y>=0."""
    y = _nonnegative("y", y)
    return -math.expm1(-y)


def S_route_a(a, L):
    """Real-antiderivative route for the shared base integral."""
    a = _nonnegative("a", a)
    L = _positive("L", L)
    b = math.pi / L
    return b * b * (1.0 + math.exp(-a * L)) / (a * a + b * b)


def arm_areas(kappa, L, n0, DX):
    """Nominal weighted areas. Not invoked by the disabled CLI."""
    kappa = _nonnegative("kappa", kappa)
    L = _positive("L", L)
    n0 = _positive("n0", n0)
    DX = _positive("DX", DX)
    if 4.0 * kappa * L > 0.1 + 1e-15:
        raise Refusal("kappaT_out_of_regime")
    s1 = S_route_a(kappa, L)
    s2 = S_route_a(2.0 * kappa, L)
    decay4 = one_minus_exp_neg(4.0 * kappa * L)
    return {
        "S1": s1,
        "S2": s2,
        "A_n_plus": -n0 * DX * math.exp(-kappa * L) * s1,
        "A_n_minus": n0 * DX * math.exp(-2.0 * kappa * L) * s1,
        "A_n2_plus": -n0 * n0 * s2 * math.exp(-2.0 * kappa * L) * decay4,
        "A_n2_minus": -n0 * n0 * s2 * decay4,
    }


def leg_witnesses(kappa, L, n0, DX):
    """Per-leg Route-A contributions, including held legs (zero areas)."""
    kappa = _nonnegative("kappa", kappa)
    L = _positive("L", L)
    n0 = _positive("n0", n0)
    DX = _positive("DX", DX)
    s1 = S_route_a(kappa, L)
    s2 = S_route_a(2.0 * kappa, L)
    legs = []
    spec = [
        ("plus", 0, L, 0.0, 0.0), ("plus", 1, DX, -1.0, -1.0),
        ("plus", 2, 0.0, 0.0), ("plus", 3, 0.0, 1.0, 1.0),
        ("minus", 0, 0.0, -1.0, -1.0), ("minus", 1, 0.0, 0.0),
        ("minus", 2, DX, 1.0, 1.0), ("minus", 3, 0.0, 0.0),
    ]
    fixed = []
    for item in spec:
        tau, index, x_factor = item[0], item[1], item[2]
        if tau == "plus" and index == 3:
            delay, sign = 3.0 * L, 1.0
        elif tau == "plus" and index == 1:
            delay, sign = L, -1.0
        elif tau == "minus" and index == 0:
            delay, sign = 0.0, -1.0
        elif tau == "minus" and index == 2:
            delay, sign = 2.0 * L, 1.0
        else:
            delay, sign = index * L, 0.0
        a_n = sign * x_factor * n0 * math.exp(-kappa * delay) * s1 if sign else 0.0
        a_n2 = sign * n0 * n0 * math.exp(-2.0 * kappa * delay) * s2 if sign else 0.0
        legs.append({"arm": tau, "leg": index, "delay": delay,
                     "A_n": a_n, "A_n2": a_n2})
        fixed.append(a_n2)
    return legs


def fixed_stage_areas(kappa, L, n0):
    kappa = _nonnegative("kappa", kappa)
    L = _positive("L", L)
    n0 = _positive("n0", n0)
    s2 = S_route_a(2.0 * kappa, L)
    i_rise = -s2
    a_n2 = n0 * n0 * i_rise * one_minus_exp_neg(4.0 * kappa * L)
    return {"A_n": 0.0, "A_n2": a_n2, "I_rise": i_rise}


def force_residual_bound(eta, hbar, b_sigma, n0, kappa, T, eps_max, tv):
    """Division-free bound over all legs, held legs included."""
    hbar = _positive("hbar", hbar)
    n0 = _positive("n0", n0)
    kappa = _nonnegative("kappa", kappa)
    T = _positive("T", T)
    eps_max = require_finite(eps_max)
    tv = _nonnegative("tv", tv)
    for value in (eta, b_sigma):
        require_finite(value)
    if eps_max < 0.0 or eps_max >= 1.0:
        raise Refusal("imbalance_guard_failed")
    root = math.sqrt(1.0 - eps_max * eps_max)
    decay2 = one_minus_exp_neg(2.0 * kappa * T)
    int_n_dt = n0 * (one_minus_exp_neg(kappa * T) / kappa if kappa > 0 else T)
    mdot_tv = kappa * eps_max * int_n_dt + (2.0 * abs(float(eta)) / hbar) * tv
    coeff = abs(float(eta) * float(b_sigma))
    term_main = coeff * n0 * n0 * (1.0 - root) * 4.0
    term_decay = coeff * eps_max * eps_max / root * n0 * n0 * decay2 * 0.5
    term_mdot = coeff * eps_max / root * n0 * mdot_tv
    total = term_main + term_decay + term_mdot
    require_finite(total)
    return {"term_main": term_main, "term_decay": term_decay,
            "term_mdot": term_mdot, "total": total, "mdot_tv_bound": mdot_tv}


def contrasts(eta, b_P, hbar, areas):
    hbar = _positive("hbar", hbar)
    for name in ("eta", "b_P"):
        value = eta if name == "eta" else b_P
        if isinstance(value, bool) or not isinstance(value, (int, float)) \
                or not math.isfinite(float(value)):
            raise Refusal("input_invalid")
    eta = float(eta)
    b_P = float(b_P)
    out = {}
    for tau in ("plus", "minus"):
        a_n = require_finite(areas["A_n_" + tau])
        a_n2 = require_finite(areas["A_n2_" + tau])
        dpsi = -(4.0 * eta * b_P / hbar) * a_n
        dj = -2.0 * eta * b_P * a_n2
        out["DeltaPsi_" + tau] = dpsi
        out["DeltaJ_" + tau] = dj
        out["closure_" + tau] = hbar * dpsi * a_n2 - 2.0 * dj * a_n
    return out


def imbalance_guard_values(eta, hbar, b_sigma, chi0, DX, kappa, T, n0, m0=0.0):
    """Guard values without threshold refusal; eps_max may be >=1."""
    hbar = _positive("hbar", hbar)
    DX = _positive("DX", DX)
    T = _positive("T", T)
    n0 = _positive("n0", n0)
    kappa = _nonnegative("kappa", kappa)
    for value in (eta, b_sigma, chi0, m0):
        require_finite(value)
    eta, b_sigma, chi0, m0 = float(eta), float(b_sigma), float(chi0), float(m0)
    tv = n0 * n0 * (
        2.0 * abs(b_sigma) * DX
        + (abs(chi0) + abs(b_sigma) * DX) * one_minus_exp_neg(2.0 * kappa * T)
    )
    n_min = n0 * math.exp(-kappa * T)
    eps_max = (math.exp(-kappa * T) * abs(m0)
               + (2.0 * abs(eta) / hbar) * tv) / n_min
    require_finite(eps_max)
    require_finite(tv)
    return {"TV": tv, "n_min": n_min, "eps_max": eps_max, "b_sigma": b_sigma}


def imbalance_guard(eta, hbar, b_sigma, chi0, DX, kappa, T, n0, m0=0.0):
    values = imbalance_guard_values(eta, hbar, b_sigma, chi0, DX, kappa, T, n0,
                                    m0=m0)
    if values["eps_max"] >= 1.0:
        raise Refusal("imbalance_guard_failed")
    return {"TV": values["TV"], "n_min": values["n_min"],
            "eps_max": values["eps_max"]}


def sideband_bound(hbar, c, B, omega0, delta_d, N_tot):
    hbar = _positive("hbar", hbar)
    c = _positive("c", c)
    B = _nonnegative("B", B)
    omega0 = _positive("omega0", omega0)
    delta_d = _nonnegative("delta_d", delta_d)
    N_tot = _nonnegative("N_tot", N_tot)
    return (hbar / c) * (B + omega0 * delta_d) * N_tot


def classify(name, guards):
    """Per-quantity state. guards maps guard name to True/False/reason."""
    if guards.get("measured_requested"):
        return {"quantity": name, "state": "instrument_unproved",
                "reason": "measured_claim_requested"}
    for guard, reason in (
        ("chart_interior", "outside_chart"),
        ("damping_isotropic", "damping_not_isotropic"),
        ("collection_aligned", "collection_unaligned"),
        ("axial_matched", "axial_direction_mismatch"),
        ("kappaT_regime", "kappaT_out_of_regime"),
        ("imbalance_guard", "imbalance_guard_failed"),
        ("history_matched", "history_unmatched"),
        ("drive_off", "drive_not_off_in_window"),
    ):
        if guards.get(guard) is not True:
            return {"quantity": name, "state": "nominal_refused", "reason": reason}
    return {"quantity": name, "state": "nominal_verified", "reason": None}


def main(argv=None):
    raise SystemExit("launch_disabled: execution_authorised=false")


if __name__ == "__main__":
    main()
