"""Strict protocol parsing for the PF-002 mechanism hypotheses study, version 1.

Virtual lab - simulated experiment tooling. The study and its wrapper share this
one parser, so they cannot disagree. Bytes are bounded first, then JSON is parsed
strictly, then every consumed field is compared with its frozen value and exact
type before any list is walked. A digest of everything but the lifecycle fields
is pinned here, so an approval can change authority and nothing else.
"""

import hashlib
import json
import math
from pathlib import Path
import unicodedata

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-mechanism-hypotheses-v1-protocol.json"
ENVIRONMENT = "Virtual lab - simulated experiment"
MAX_INPUT_BYTES = 1048576
MAX_JSON_DEPTH = 16
MAX_JSON_NODES = 200000
LIFECYCLE_KEYS = ("protocol_state", "protocol_revision", "execution_authorised",
                  "authorised_modes", "status", "stage_authority")
SCIENCE_DIGEST = ("sha256:3ffa242a5caa2877ba9551b24c66616f5"
                  "790d24d4025eaa4e59aea71dbb817a9")
LIFECYCLE_STATES = (
    {"protocol_state": "proposed", "protocol_revision": 6,
     "execution_authorised": False, "authorised_modes": []},
    {"protocol_state": "pre_registered", "protocol_revision": 7,
     "execution_authorised": True, "authorised_modes": ["deterministic_primary"]})
LIMITS = {
    "maximum_fixture_seconds": 1200, "maximum_fixture_workers": 1,
    "maximum_runtime_seconds_including_cleanup": 900, "maximum_study_processes": 1,
    "maximum_retained_bytes": 2097152, "maximum_parser_nodes": 200000,
    "maximum_json_depth": 16, "maximum_stdout_bytes": 65536,
    "maximum_stderr_bytes": 65536, "network_calls": 0, "new_dependencies": 0}
FROZEN = (
    (("study",), "pf002-mechanism-hypotheses-v1"),
    (("environment",), ENVIRONMENT),
    (("required_margin_newtons",), 1e-12),
    (("source_scope", "wavelength_m"), 1.55e-06),
    (("source_scope", "aperture_radius_m"), 3.1e-05),
    (("source_scope", "separation_m"), 3.1e-05),
    (("source_scope", "feed_watts"), 1.0),
    (("retained_scalars", "B1_S01_half_width_newtons"), 7.284e-12),
    (("retained_scalars", "B1_S05_half_width_newtons"), 1.3502e-11),
    (("frozen_domains", "R_stroke_metres"), 1e-06),
    (("frozen_domains", "ell_metres"), [0.1, 0.2, 0.4]),
    (("frozen_domains", "f_hertz"), 70000000.0),
    (("coupling_grids", "eta"), [-1.0, -0.1, -0.001, -4e-09, 0.0, 4e-09, 0.001, 0.1, 1.0]),
    (("coupling_grids", "g_per_GeV"), [0.0, 6.6e-11, 5.45e-07, 0.001, 1.0, 1000.0, 677000.0]),
    (("coupling_grids", "h"), [-1.0, -0.1, -0.001, -1e-06, 0.0, 1e-06, 0.001, 0.1, 1.0]),
    (("configurations", "count"), 36),
    (("configurations", "cap"), 48),
    (("limits",), LIMITS),
    (("runs", "deterministic_primary"), 1),
    (("runs", "exploratory_stochastic"), 0),
    (("runs", "confirmatory_stochastic"), 0),
    (("runs", "retries"), 0),
    (("seeds", "fixture_and_witness"), [9401, 9404]),
    (("seeds", "exploratory"), None),
    (("seeds", "confirmatory"), None),
    (("lean_record", "maximum_bytes_per_configuration"), 16384),
    (("discriminators",), {"C1": ["I4", "I5"], "C2": ["I2", "I3"], "C3": ["I6", "I7"]}),
    (("mathematical_freeze", "constants", "c_metres_per_second"), 299792458.0),
    (("mathematical_freeze", "constants", "h_joule_second"), 6.62607015e-34),
    (("mathematical_freeze", "constants", "e_coulomb"), 1.602176634e-19),
    (("mathematical_freeze", "constants", "mu_0_newton_per_ampere_squared"), 1.25663706127e-06),
    (("mathematical_freeze", "power_map", "orthogonal_channels_P_rad_watts_at_s_1"), 1.0),
    (("mathematical_freeze", "power_map", "orthogonal_channel_power_watts"), 0.5),
    (("mathematical_freeze", "power_map", "C3_P0_watts"), 0.62245),
    (("mathematical_freeze", "proposition_M", "rectangle_R_nu"),
     [[0, 1], [1, 1], [1, -1], [0, -1]]),
    (("mathematical_freeze", "quadrature", "retained_panels"), [800, 1600]),
    (("mathematical_freeze", "quadrature", "retained_relative_tolerance"), 1e-07),
    (("mathematical_freeze", "quadrature", "oracle_float_relative_tolerance"), 1e-06),
    (("mathematical_freeze", "C2_scope", "maximum_f_est"), 0.01),
    (("mathematical_freeze", "C2_scope", "maximum_g_omega"), 0.1),
    (("c1_context", "row_context"), {"variant": "C1-E", "situation": "open_path", "a_inf": 0.0}),
    (("adverse_cases", "probes"), {
        "epsilon": 0.1, "a_inf": 0.5, "g_per_GeV": 1000.0, "h": 0.1,
        "reflection_amplitude": 0.01, "transferred_abs_eta_illustrative": 4e-09}),
    (("adverse_cases", "match_relative_tolerance"), 1e-09),
    (("primary_record", "kind"), "mechanism_hypotheses_primary"),
    (("primary_record", "fixture_kind"), "mechanism_hypotheses_fixture"),
    (("primary_record", "source_mode"), "deterministic_primary"),
    (("primary_record", "required_hypotheses"),
     ["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]))


def _unique(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate protocol key")
        result[key] = value
    return result


def _reject_constant(token):
    raise ValueError(f"non-finite protocol constant {token}")


def _finite_float(token):
    value = float(token)
    if not math.isfinite(value):
        raise ValueError("non-finite protocol number")
    return value


def walk(value, depth=1):
    """Yield every value and key, refusing depth past the declared limit."""
    if depth > MAX_JSON_DEPTH:
        raise ValueError("nesting exceeds its limit")
    yield value
    if isinstance(value, dict):
        for key, item in value.items():
            yield key
            yield from walk(item, depth+1)
    elif isinstance(value, list):
        for item in value:
            yield from walk(item, depth+1)


def same(value, expected):
    """Equal in value and exact type, so True is not 1 and 1 is not 1.0.

    Lengths and key sets are compared before any element is touched.
    """
    if type(value) is not type(expected):
        return False
    if isinstance(expected, list):
        return (len(value) == len(expected)
                and all(same(a, b) for a, b in zip(value, expected)))
    if isinstance(expected, dict):
        return (len(value) == len(expected) and value.keys() == expected.keys()
                and all(same(value[key], expected[key]) for key in expected))
    return value == expected


def field(protocol, path):
    value = protocol
    for key in path:
        if not isinstance(value, dict) or key not in value:
            raise ValueError(f"protocol lacks {'.'.join(path)}")
        value = value[key]
    return value


def science_digest(protocol):
    """sha256 of the canonical twin without its lifecycle fields."""
    science = {key: value for key, value in protocol.items()
               if key not in LIFECYCLE_KEYS and not key.startswith("revision_")}
    text = json.dumps(science, sort_keys=True, separators=(",", ":"), allow_nan=False)
    return "sha256:"+hashlib.sha256(text.encode("utf-8")).hexdigest()


def check_lifecycle(protocol):
    found = {key: protocol.get(key) for key in LIFECYCLE_STATES[0]}
    if not any(same(found, state) for state in LIFECYCLE_STATES):
        raise ValueError("protocol lifecycle is not a declared state")


def check_values(protocol):
    if not isinstance(protocol, dict):
        raise ValueError("protocol is not an object")
    check_lifecycle(protocol)
    for path, expected in FROZEN:
        if not same(field(protocol, path), expected):
            raise ValueError(f"{'.'.join(path)} differs from its frozen value")
    # Two fields define nu. A disagreement is refused, and neither one wins.
    nu = field(protocol, ("mechanisms", "C3", "definitions", "nu"))
    if nu != field(protocol, ("frozen_domains", "nu")):
        raise ValueError("the definitions of nu disagree")
    if not isinstance(nu, str) or not nu.startswith("minus_sin_phi"):
        raise ValueError("nu differs from its frozen sign")
    if science_digest(protocol) != SCIENCE_DIGEST:
        raise ValueError("protocol science differs from its pinned digest")


def parse_protocol(data):
    """Bounds, then strict JSON, then frozen values, before anything is used."""
    if not isinstance(data, bytes) or len(data) > MAX_INPUT_BYTES:
        raise ValueError("protocol is not bounded bytes")
    try:
        protocol = json.loads(data.decode("utf-8"), object_pairs_hook=_unique,
                              parse_constant=_reject_constant,
                              parse_float=_finite_float)
    except RecursionError as error:
        raise ValueError("nesting exceeds its limit") from error
    nodes = 0
    for item in walk(protocol):
        nodes += 1
        if nodes > MAX_JSON_NODES:
            raise ValueError("protocol exceeds its node limit")
        if isinstance(item, str) and not unicodedata.is_normalized("NFC", item):
            raise ValueError("protocol string is not NFC")
    check_values(protocol)
    return protocol


def load_protocol(path=ROOT/PROTOCOL_FILE):
    with open(path, "rb") as source:
        data = source.read(MAX_INPUT_BYTES+1)
    return parse_protocol(data)


def primary_authorised(protocol):
    return (same(protocol["execution_authorised"], True)
            and same(protocol["authorised_modes"], ["deterministic_primary"]))


def launch_limits(protocol, mode, grace, kill):
    """Deadline and caps for one launch. Cleanup must fit inside the deadline."""
    limits = protocol["limits"]
    if mode == "fixture":
        total = limits["maximum_fixture_seconds"]
    elif mode == "deterministic_primary":
        total = limits["maximum_runtime_seconds_including_cleanup"]
    else:
        raise ValueError("unknown mode")
    seconds = total-grace-kill
    if not (isinstance(seconds, (int, float)) and math.isfinite(seconds) and seconds > 0):
        raise ValueError("cleanup does not fit inside the deadline")
    return {"seconds": seconds, "result": limits["maximum_retained_bytes"],
            "stdout": limits["maximum_stdout_bytes"],
            "stderr": limits["maximum_stderr_bytes"]}
