"""Dormant report builder and disabled entry point, C3-S completion.

Virtual lab - simulated experiment tooling. The builder is concrete: it
assembles the canonical future report record from checker outputs and
provenance, validates the frozen record caps, and writes no-clobber. It is
structurally tested only with synthetic stub check subsets; dispatching
the complete scientific report during qualification is prohibited here.
`main` always refuses in version 1: both twin launch flags are false and
report execution is not authorised. Stdlib plus this study's checker for
the strict launch parser; no old study is imported.
"""

import json
import math
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pf002_c3_completion_checker_v1 as checker

HERE = os.path.dirname(os.path.abspath(__file__))
TWIN = os.path.join(HERE, "pf002-c3-completion-v1-protocol.json")
RECORD_CAP_BYTES = 262144
RECORD_CAP_NODES = 20000
FROZEN_CHECKS = tuple(checker.CHECK_GUARDS)


def _fields(names, schema):
    return dict.fromkeys(names.split(), schema)


# Each object is closed. A one-element list describes repeated items.
_RATIONAL = re.compile(r"-?(?:0|[1-9][0-9]*)(?:/[1-9][0-9]*)?")
_DECIMAL = re.compile(r"-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")
_TERM = {"powers": "powers", "coefficient": "rational"}
_RAT = {"r_denominator_power": "r_power", "terms": [_TERM]}
_CURVATURE = _fields("F_mphi F_nphi F_Xphi F_Xn F_Xm F_nm", _RAT)
_VELOCITY = _fields("n thetabar m phi", _fields("hbar_scaled_velocity expected", _RAT))
_AC = {"first_derivative": "rational",
       **_fields("bound_rad epsilon_max z_min relative_allowance", float)}
_WITNESSES = {
    "VS1": _CURVATURE,
    "VS2": _fields("dnu_coefficient ds_coefficient", _RAT),
    "VS3": {"cleared_row_residual": _RAT, "m0_row_samples": [
        _fields("ndot xdot partial_t_chibar computed_mdot expected_mdot", "rational")]},
    "VS4": _fields("computed expected", _RAT),
    "VS5": _fields("Ks Ks_reversed Ls Ls_reversed AXnu Bsnu Ks_depth collapsed", "rational"),
    "VS6": {"cleared_closure_residual": _RAT},
    "VS7": _fields("d_X expected", [_TERM]),
    "VS8": {"OM-S": _VELOCITY, "OM-2": _VELOCITY, "adverse_static_drive": {
        **_fields("OM-S_signed_projection OM-2_signed_projection "
                  "readout_derivative Delta bath_phi_velocity", "rational"),
        "projection_convention": "+F_Xphi * phi_velocity",
    }},
    "VS9": _fields("d_X d_Y derivative_sum", [_TERM]),
    "VS10": {"computed": float, **_fields("reference relative_error relative_limit", "decimal")},
    "VS11": _CURVATURE,
    "VS12": {
        **_fields("phase_numerator mechanical_difference", _RAT),
        **_fields("phase_numerator_at_point phase_denominator_at_point phase_derivative "
                  "gradient_at_chibar_zero local_phase_curvature nonzero_product_quotient",
                  "rational"),
        "zero_product_state": "quotient_undefined",
        **_fields("collapsed_zero travel_matches spring_integral_zero", bool),
    },
    "AC-T1": {**_AC, "second_derivative": "rational", "residual_rad": float},
    "AC-T2": {**_AC, "increment_rad": float},
}


def _matches(value, schema):
    if isinstance(schema, dict):
        return (type(value) is dict and value.keys() == schema.keys()
                and all(_matches(value[key], field) for key, field in schema.items()))
    if isinstance(schema, list):
        return (type(value) is list and len(value) <= checker.MAX_TERMS
                and all(_matches(item, schema[0]) for item in value))
    if schema == "powers":
        return (type(value) is dict and len(value) <= len(checker.VARS)
                and all(name in checker.IDX or name in {"mu", "D", "E", "P"}
                        for name in value)
                and all(type(power) is int and abs(power) <= checker.MAX_DEGREE
                        for power in value.values()))
    if schema == "r_power":
        return type(value) is int and 0 <= value <= 3
    if schema is float:
        return type(value) is float and math.isfinite(value)
    if isinstance(schema, str):
        if type(value) is not str or len(value) > 160:
            return False
        if schema == "rational":
            return _RATIONAL.fullmatch(value) is not None
        if schema == "decimal":
            return _DECIMAL.fullmatch(value) is not None
        return value == schema
    return type(value) is schema


def twin_flags(path=TWIN):
    with open(path, "rb") as stream:
        data = stream.read(131073)
    if len(data) > 131072:
        raise ValueError("twin_bytes")
    twin = checker.parse_launch_protocol(data)
    return (twin["execution_authorised"], twin["fixture_verification_authorised"],
            twin["authorised_modes"])


def _nodes(value):
    count, stack = 0, [value]
    while stack:
        node = stack.pop()
        count += 1
        if isinstance(node, dict):
            stack.extend(node.values())
        elif isinstance(node, list):
            stack.extend(node)
    return count


def build_report_record(checks, provenance, allow_partial=False):
    """Assemble (never dispatch) the canonical record for given checks.

    Each input row must match the original checker-issued snapshot before
    its outcome, quantities and guards are decoded and shape-checked.
    Node count and a byte estimate are checked before serialisation.
    """
    unknown = set(checks) - set(FROZEN_CHECKS)
    if unknown:
        raise ValueError(f"unknown_checks:{sorted(unknown)}")
    if set(checks) != set(FROZEN_CHECKS) and not allow_partial:
        raise ValueError("incomplete_checks_require_allow_partial")
    witnesses = {}
    for name, row in checks.items():
        value = checker.report_witness(name, row)
        if (type(value) is not dict or value.keys() != {"outcome", "quantity", "guard"}
                or type(value["outcome"]) is not bool
                or value["guard"] != list(checker.CHECK_GUARDS[name])
                or not _matches(value["quantity"], _WITNESSES[name])
                or (name == "VS3" and len(value["quantity"]["m0_row_samples"]) != 3)):
            raise ValueError(f"invalid_check_witness:{name}")
        witnesses[name] = value
    predicates = {"VS10": "floating_1e-12", "AC-T1": "floating_formula_1e-9",
                  "AC-T2": "floating_formula_1e-9"}
    required_prov = {"source_sha256", "git_head", "runtime"}
    if not isinstance(provenance, dict) \
            or not required_prov.issubset(provenance) \
            or any(not isinstance(provenance[k], str)
                   for k in required_prov):
        raise ValueError("provenance_binding")
    record = {"study": "pf002-c3-completion-v1-formal-algebra",
              "checks": {name: {
                  "outcome": witnesses[name]["outcome"],
                  "predicate": predicates.get(name, "exact_formal"),
                  "quantity": witnesses[name]["quantity"],
                  "guard": witnesses[name]["guard"]}
                  for name in sorted(checks)},
              "partial": set(checks) != set(FROZEN_CHECKS),
              "provenance": provenance,
              "interpretation": "formal_algebra_only_no_physical_inference"}
    if _nodes(record) > RECORD_CAP_NODES:
        raise ValueError("record_cap_nodes_pre")
    estimate = len(str(record)) * 2 + 4096
    if estimate > RECORD_CAP_BYTES:
        raise ValueError("record_cap_bytes_pre")
    data = (json.dumps(record, sort_keys=True, indent=1, allow_nan=False) + "\n").encode()
    if len(data) > RECORD_CAP_BYTES:
        raise ValueError("record_cap_bytes")
    return data


def write_record_no_clobber(path, data):
    with open(path, "xb") as stream:
        stream.write(data)


def main(argv):
    try:
        execution, fixture, modes = twin_flags()
    except Exception as error:  # fail closed, type only
        sys.stderr.write(f"refused: twin_unreadable:{type(error).__name__}\n")
        return 2
    if execution is not False or fixture is not False or modes != []:
        sys.stderr.write("refused: unexpected launch-flag state, "
                         "separate review required\n")
        return 2
    sys.stderr.write("refused: report execution not authorised; both "
                     "launch flags are false\n")
    return 2


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
