#!/usr/bin/env python3
"""Fixed, offline teaching calculations; not a service reliability measurement."""

import itertools
import json
import math
import platform
import sys


def validate(n, alpha):
    if type(n) is not int or n < 1:
        raise ValueError("n must be a positive integer")
    if not math.isfinite(alpha) or not 0 < alpha < 1:
        raise ValueError("alpha must be finite and strictly between 0 and 1")


def zero_upper(n, alpha=0.05):
    validate(n, alpha)
    return -math.expm1(math.log(alpha) / n)


def pmf(n, p):
    # Only the small fixed n used below is intended for this direct sum.
    return [math.comb(n, k) * p**k * (1 - p)**(n - k)
            for k in range(n + 1)]


def cdf(x, n, p):
    return math.fsum(math.comb(n, k) * p**k * (1 - p)**(n - k)
                     for k in range(x + 1))


def exact_upper(x, n, alpha=0.05):
    validate(n, alpha)
    if type(x) is not int or not 0 <= x <= n:
        raise ValueError("x must be an integer between 0 and n")
    if x == n:
        return 1.0
    low, high = 0.0, 1.0
    for _ in range(64):
        mid = (low + high) / 2
        if cdf(x, n, mid) > alpha:
            low = mid
        else:
            high = mid
    return (low + high) / 2


def main():
    checks = []

    def check(name, condition):
        if not condition:
            raise AssertionError(name)
        checks.append({"name": name, "passed": True})

    alpha = 0.05
    bounds = [{"n": n, "failures": 0,
               "upper_one_sided_95": zero_upper(n), "three_over_n": 3 / n}
              for n in (1, 5, 100, 299, 300, 1000, 2995)]
    check("closed form agrees with CDF inversion",
          all(abs(row["upper_one_sided_95"] - exact_upper(0, row["n"])) < 1e-12
              for row in bounds))
    zero_probabilities = [{"n": 100, "true_p": p,
                           "probability_of_zero_failures": (1 - p)**100}
                          for p in (0.0, 0.01, 0.03, 1.0)]

    plans = []
    for target in (0.01, 0.001):
        n = math.ceil(math.log(alpha) / math.log1p(-target))
        plans.append({"target_p": target, "minimum_n_if_zero_failures": n,
                      "upper_at_n": zero_upper(n),
                      "upper_at_previous_n": zero_upper(n - 1),
                      "probability_of_zero_at_target": (1 - target)**n})
    check("sample size thresholds are minimal integers",
          all(row["upper_at_n"] <= row["target_p"] < row["upper_at_previous_n"]
              for row in plans))
    batch_zero = (1 - 0.01)**299
    selected_batches = {"true_p": 0.01, "trials_per_batch": 299,
                        "independent_batches": 10,
                        "zero_probability_in_one_batch": batch_zero,
                        "probability_at_least_one_zero_batch": 1 - (1 - batch_zero)**10}
    check("selecting among ten batches increases the chance of a zero batch",
          selected_batches["probability_at_least_one_zero_batch"] > batch_zero)
    one_failure_upper = exact_upper(1, 100)
    check("one observed failure gives a larger upper bound",
          one_failure_upper > zero_upper(100))
    check("all failures allow upper endpoint one", exact_upper(100, 100) == 1.0)
    check("n=1, x=0 gives upper 0.95", abs(zero_upper(1) - 0.95) < 1e-15)
    check("x=n-1 agrees with independent closed form",
          abs(exact_upper(19, 20) - (1 - alpha)**(1 / 20)) < 1e-12)

    coverage = []
    residuals = []
    for n in (20, 100):
        uppers = [exact_upper(x, n) for x in range(n + 1)]
        residuals.extend(abs(cdf(x, n, uppers[x]) - alpha) for x in range(n))
        for p in (0.0, 0.001, 0.01, 0.03, 0.1, 0.5, 0.9, 0.99, 1.0):
            weights = pmf(n, p)
            coverage.append({"n": n, "true_p": p,
                             "coverage_probability": math.fsum(
                                 w for w, upper in zip(weights, uppers)
                                 if p <= upper + 1e-14),
                             "probability_mass_sum": math.fsum(weights)})
    check("enumerated PMF masses sum to one",
          all(abs(row["probability_mass_sum"] - 1) < 1e-12 for row in coverage))
    check("18 selected parameter pairs have at least 95 percent coverage",
          all(row["coverage_probability"] >= 0.95 - 1e-12 for row in coverage))
    check("interior CDF root residuals below 1e-12", max(residuals) < 1e-12)

    # Five independent Bernoulli draws, each copied twenty times: 32 states.
    # Every observed run has marginal failure probability 0.01, but runs
    # inside a block are perfectly correlated by construction.
    p, units, repeats = 0.01, 5, 20
    states = []
    for bits in itertools.product((0, 1), repeat=units):
        failures = sum(bits)
        states.append({"observed_failures": failures * repeats,
                       "first_run_failed": bool(bits[0]),
                       "probability": p**failures * (1 - p)**(units - failures)})
    correlated = {
        "true_marginal_p": p, "independent_units": units,
        "repeats_per_unit": repeats, "observed_runs": units * repeats,
        "enumerated_states": len(states),
        "probability_of_zero_failures": math.fsum(
            s["probability"] for s in states if s["observed_failures"] == 0),
        "probability_of_zero_if_100_independent": (1 - p)**100,
        "upper_one_sided_95_for_five_units": zero_upper(units),
        "first_run_marginal_p": math.fsum(
            s["probability"] for s in states if s["first_run_failed"]),
    }
    check("32 block states preserve total mass and marginal p",
          abs(math.fsum(s["probability"] for s in states) - 1) < 1e-12
          and abs(correlated["first_run_marginal_p"] - p) < 1e-12)
    check("block-model zero probability equals five independent units",
          abs(correlated["probability_of_zero_failures"] - (1 - p)**units) < 1e-12)

    invalid = []
    for args in ((0, 0, 0.05), (0, -1, 0.05), (0, 1.5, 0.05),
                 (0, 100, 0.0), (0, 100, 1.0), (0, 100, float("nan")),
                 (-1, 100, 0.05), (101, 100, 0.05), (0.5, 100, 0.05)):
        try:
            exact_upper(*args)
        except ValueError as exc:
            invalid.append({"arguments": [repr(v) for v in args], "error": str(exc)})
        else:
            raise AssertionError(f"unexpected acceptance: {args!r}")
    check("nine invalid inputs rejected", len(invalid) == 9)

    report = {
        "date": "2026-10-26", "kind": "offline model calculations, not production tests",
        "environment": {"python": platform.python_version(), "system": platform.system(),
                        "macos": platform.mac_ver()[0], "machine": platform.machine()},
        "alpha": alpha, "zero_failure_bounds": bounds,
        "zero_failure_probabilities": zero_probabilities, "zero_failure_sample_plans": plans,
        "selection_of_best_batch": selected_batches,
        "one_failure_in_100_upper_one_sided_95": one_failure_upper,
        "zero_in_100_upper_endpoint_equal_tailed_two_sided_95": zero_upper(100, alpha / 2),
        "coverage_by_full_count_enumeration": coverage,
        "largest_CDF_root_residual": max(residuals),
        "correlated_blocks": correlated, "invalid_inputs": invalid,
        "checks": checks,
        "limits": ["Fixed n; independent Bernoulli trials with a common p for binomial bounds.",
                   "Correlated block scenario is a declared toy model, not measured dependence.",
                   "Coverage checked at 18 selected parameter pairs, not all real p.",
                   "Direct small-n floating-point sums, not a general numerical statistics library.",
                   "No production requests, deployment tests, random simulation, or R execution."]
    }
    json.dump(report, sys.stdout, ensure_ascii=False, indent=2, allow_nan=False)
    print()


if __name__ == "__main__":
    main()
