"""Synthetic score examples, not a failure-detector implementation. Original code: CC0-1.0."""
from datetime import datetime, timezone
from fractions import Fraction
from hashlib import sha256
import json
import math
from pathlib import Path
import platform


def positive(value, label):
    if not math.isfinite(value) or value <= 0:
        raise ValueError(label + " must be finite and positive")
    return value


def elapsed(value):
    if not math.isfinite(value) or value < 0:
        raise ValueError("elapsed time must be finite and nonnegative")
    return value


def exponential_phi(delay, mean):
    return elapsed(delay) / positive(mean, "mean") / math.log(10)


def normal_phi(delay, mean, sigma):
    z = (elapsed(delay) - positive(mean, "mean")) / positive(sigma, "sigma")
    # erfc avoids cancellation from subtracting a near-one normal CDF.
    tail = 0.5 * math.erfc(z / math.sqrt(2))
    if tail == 0:
        raise ValueError("normal tail underflows; use a log-survival implementation")
    return -math.log10(tail)


def hypothetical_posterior(prior, alive_tail):
    if not (0 < prior < 1 and 0 < alive_tail <= 1):
        raise ValueError("prior must be in (0,1) and alive_tail in (0,1]")
    # Assumption: a failed node cannot produce the next observed heartbeat.
    return prior / (prior + (1 - prior) * alive_tail)


def calculations():
    return {
        "parameters": {"meanSeconds": 1.0, "normalSigmaSeconds": 0.1},
        "scores": [
            {"elapsedSeconds": d,
             "normalPhi": normal_phi(d, 1.0, 0.1),
             "exponentialPhi": exponential_phi(d, 1.0)}
            for d in [1.0, 1.2, 1.5, 2.0]
        ],
        "bayes": [
            {"prior": float(prior), "aliveTail": 0.001,
             "posterior": float(hypothetical_posterior(prior, Fraction(1, 1000))),
             "posteriorExact": str(hypothetical_posterior(prior, Fraction(1, 1000)))}
            for prior in [Fraction(1, 10000), Fraction(1, 100)]
        ],
    }


def result():
    return {
        "schemaVersion": 1,
        "evidenceType": "synthetic-analytic-example",
        "generatedAt": datetime.now(timezone.utc).isoformat(),
        "sourcesReviewedOn": "2026-10-17",
        "runtime": "Python " + platform.python_version(),
        "sourceCodeSha256": sha256(Path(__file__).read_bytes()).hexdigest(),
        "license": "CC0-1.0",
        "limits": [
            "Fixed invented parameters, not fitted heartbeat data.",
            "Untruncated normal approximation; no rolling window or packet-loss model.",
            "No Cassandra runtime, pause guard, seeding, filtering or polling simulation.",
            "Bayes priors are hypothetical and are not estimated incident rates.",
            "No threshold recommendation, fleet false-alarm rate or paper reproduction."
        ],
        **calculations()
    }


if __name__ == "__main__":
    Path(__file__).with_name("results.json").write_text(
        json.dumps(result(), indent=2, allow_nan=False) + "\n", encoding="utf-8"
    )
