"""Reproduce hypothetical methodological examples, not empirical risk estimates."""
import json
import math
from pathlib import Path

BASE = Path(__file__).resolve().parent

def zero_detection_upper(n, q=1.0, alpha=0.05):
    if n <= 0 or not 0 < q <= 1 or not 0 < alpha < 1:
        raise ValueError("Require n > 0, 0 < q <= 1, 0 < alpha < 1")
    return min(1.0, -math.expm1(math.log(alpha) / n) / q)

def ppv(prevalence, sensitivity, false_positive):
    numerator = prevalence * sensitivity
    return numerator / (numerator + (1 - prevalence) * false_positive)

zero_rows = [{"n": n, "q": q, "upper_probability": zero_detection_upper(n, q)}
             for n, q in [(100, 1), (1000, 1), (1000, .5), (1000, .1), (10000, 1)]]
for row in zero_rows:
    assert math.isclose((1-row["q"]*row["upper_probability"])**row["n"], .05, abs_tol=1e-12)
assert zero_detection_upper(1, .01) == 1.0
assert zero_detection_upper(10000) < zero_detection_upper(1000)
assert zero_detection_upper(1000, .1) > zero_detection_upper(1000, .5)
assert math.isclose(ppv(.5, .9, .1), .9)

backlog = 0
for _ in range(30):
    backlog = max(0, backlog + 120 - 100)
assert backlog == 600
report = {
    "status": "passed",
    "scope": "Hypothetical arithmetic demonstrations only; no fitted or elicited catastrophe estimate.",
    "zero_detection": {"alpha": .05, "rows": zero_rows,
        "assumptions": "IID representative trials; fixed known sensitivity; confirmed event count; constant harmful-event probability."},
    "detection_chain": {"conditional_probabilities": [.8,.9,.9], "result": .8*.9*.9},
    "cluster_variance": {"n":1000,"cluster_size":20,"rho":.1,"design_effect":2.9,"variance_equivalent_n":1000/2.9,
        "warning":"Not an exact rare-event bound or a correction for the audited incidents."},
    "alert_precision": {"prevalence":.0001,"sensitivity":.9,"false_positive_rate":.01,
        "ppv":ppv(.0001,.9,.01),"expected_true_alerts_per_million":90,
        "expected_false_alerts_per_million":9999},
    "amdahl": [{"serial_fraction":.1,"workers":n,"speedup":1/(.1+.9/n)} for n in [1,10,100]],
    "validation_backlog": {"days":30,"arrivals_per_day":120,"validations_per_day":100,"final_backlog":backlog},
    "policy_break_even": [{"net_other_cost":c,"conditional_catastrophe_loss":10000,"required_probability_reduction":c/10000}
                         for c in [1,10,100]],
    "constant_hazard": {"hazard_per_year":.001,"years":10,"cumulative_probability":-math.expm1(-.001*10)},
    "verification": "Numerical substitution in defining tail equation; monotonicity, clipping, Bayes-rule and backlog controls passed."
}
(BASE / "calculation-results.json").write_text(json.dumps(report, indent=2)+"\n", encoding="utf-8")
print(json.dumps({"status":report["status"], "examples":8, "file":"calculation-results.json"}))
