"""Non-canonical, interval-based feasibility screen for a phase-paired bench test.

All inputs are caller-supplied design bounds, not measured capabilities. No
probability, independence, averaging gain or hardware readiness is inferred.
"""

from __future__ import annotations

import argparse
import json
import math
import re
import sys
from dataclasses import dataclass

LIGHT_SPEED_M_S = 299_792_458


def numeric_option(text: str) -> float:
    """A bounded ASCII decimal option, not a protocol or identity parser."""
    if len(text) > 64 or not re.fullmatch(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?", text):
        raise argparse.ArgumentTypeError("expected an ASCII decimal of at most 64 characters")
    value = float(text)
    if not math.isfinite(value) or (value == 0 and math.copysign(1, value) < 0):
        raise argparse.ArgumentTypeError("number must be finite and not negative zero")
    return value


def parse_options(parser: argparse.ArgumentParser) -> argparse.Namespace:
    arguments = sys.argv[1:]
    if len(arguments) > 32 or sum(len(value.encode("utf-8")) for value in arguments) > 4096:
        parser.error("command exceeds 32 arguments or 4096 UTF-8 input bytes")
    return parser.parse_args(arguments)


class OnceFloat(argparse.Action):
    """Reject repeated numeric options instead of silently taking the last."""

    def __call__(self, parser, namespace, values, option_string=None):
        if getattr(namespace, self.dest, None) is not None:
            parser.error(f"repeated option: {option_string}")
        setattr(namespace, self.dest, values)


def bounded(value: float, lower: float, upper: float, name: str) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{name} must be a finite number")
    if not lower <= value <= upper or not math.isfinite(value):
        raise ValueError(f"{name} is outside its finite allowed range")
    return float(value)


@dataclass(frozen=True)
class PhaseBudget:
    """Bounds for total escaping power and the measured portion of its pattern.

    observed_moment is the axial direction-cosine average of observed power,
    not the average over the full sphere. Unobserved power can point anywhere.
    Every uncertainty is an absolute interval half-width, not a standard error.
    """

    power_watts: float
    power_bound_watts: float
    observed_fraction: float
    observed_fraction_bound: float
    observed_moment: float
    observed_moment_bound: float

    def recoil_interval(self) -> tuple[float, float]:
        power = bounded(self.power_watts, 0, 1e9, "radiated power")
        power_bound = bounded(self.power_bound_watts, 0, 1e9, "power bound")
        fraction = bounded(self.observed_fraction, 0, 1, "observed fraction")
        fraction_bound = bounded(self.observed_fraction_bound, 0, 1, "fraction bound")
        moment = bounded(self.observed_moment, -1, 1, "observed moment")
        moment_bound = bounded(self.observed_moment_bound, 0, 2, "moment bound")
        # Reject inconsistent bounds rather than silently clipping missing power
        # or inventing a narrower interval than the caller supplied.
        if not 0 <= power - power_bound <= power + power_bound <= 1e9:
            raise ValueError("power interval must stay within zero to 1 GW")
        if not 0 <= fraction - fraction_bound <= fraction + fraction_bound <= 1:
            raise ValueError("observed fraction interval must stay within zero to one")
        if not -1 <= moment - moment_bound <= moment + moment_bound <= 1:
            raise ValueError("observed moment interval must stay within minus one to one")
        moments = [
            coverage * observed + (1 - coverage) * unknown
            for coverage in (fraction - fraction_bound, fraction + fraction_bound)
            for observed in (moment - moment_bound, moment + moment_bound)
            for unknown in (-1, 1)
        ]
        forces = [
            -radiated * axial / LIGHT_SPEED_M_S
            for radiated in (power - power_bound, power + power_bound)
            for axial in (min(moments), max(moments))
        ]
        return min(forces), max(forces)


def screen(
    forward: PhaseBudget,
    reverse: PhaseBudget,
    differential_noise_bound_newtons: float,
    differential_nuisance_bound_newtons: float,
) -> dict[str, object]:
    """Screen whether a predicted reversal is separated from bounded artifacts.

    Conservative subtraction does not assume correlated errors cancel. Sensor
    and nuisance bounds apply to the paired difference, not to each sample.
    A positive margin only warrants feasibility follow-up, not acceptance.
    """
    noise = bounded(differential_noise_bound_newtons, 0, 10, "differential noise bound")
    nuisance = bounded(differential_nuisance_bound_newtons, 0, 10, "differential nuisance bound")
    low_a, high_a = forward.recoil_interval()
    low_b, high_b = reverse.recoil_interval()
    low, high = low_b - high_a, high_b - low_a
    lower_magnitude = 0.0 if low <= 0 <= high else min(abs(low), abs(high))
    # Do not let a last-bit rounding artefact turn equality into a positive
    # screen. This is a numerical guard, not a metrological uncertainty.
    arithmetic_guard = 64 * math.ulp(max(abs(low), abs(high), noise, nuisance))
    margin = lower_magnitude - noise - nuisance - arithmetic_guard
    return {
        "status": "conditional_design_screen_not_measurement",
        "forward_recoil_interval_newtons": [low_a, high_a],
        "reverse_recoil_interval_newtons": [low_b, high_b],
        "reverse_minus_forward_interval_newtons": [low, high],
        "differential_noise_bound_newtons": noise,
        "differential_nuisance_bound_newtons": nuisance,
        "minimum_predicted_difference_newtons": lower_magnitude,
        "arithmetic_guard_newtons": arithmetic_guard,
        "resolution_margin_newtons": margin,
        "screen": "discriminating_under_supplied_bounds" if margin > 0 else "unresolved_under_supplied_bounds",
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    fields = tuple(PhaseBudget.__dataclass_fields__)
    for phase in ("forward", "reverse"):
        for field in fields:
            parser.add_argument(f"--{phase}-{field.replace('_', '-')}", type=numeric_option,
                                action=OnceFloat, required=True)
    parser.add_argument("--differential-noise-bound-newtons", type=numeric_option, action=OnceFloat, required=True)
    parser.add_argument("--differential-nuisance-bound-newtons", type=numeric_option, action=OnceFloat, required=True)
    args = vars(parse_options(parser))
    try:
        phases = [PhaseBudget(**{field: args[f"{phase}_{field}"] for field in fields})
                  for phase in ("forward", "reverse")]
        result = screen(*phases, args["differential_noise_bound_newtons"],
                        args["differential_nuisance_bound_newtons"])
    except ValueError as error:
        parser.error(str(error))
    print(json.dumps(result, sort_keys=True, separators=(",", ":"), allow_nan=False))


if __name__ == "__main__":
    main()
