#!/usr/bin/env python3
"""Reproduce Cateo's xGOT worked examples with Python's standard library.

No network, credentials, provider feeds, raw licensed data, fitting or simulation.
The Poisson-binomial calculation uses the exact distribution recurrence, subject
to floating-point arithmetic. The published-aggregate audit uses Decimal for the
rounding envelope. Source authors already derive missing-probability bounds.
"""

import argparse
from decimal import Decimal
import itertools
import json
import math
from pathlib import Path
import sys


MAX_SAFE_INTEGER = 9007199254740991


def count(value, name):
    if type(value) is not int or not 0 <= value <= MAX_SAFE_INTEGER:
        raise ValueError(f"{name} must be a non-negative safe integer")


def probability(value, name):
    if (isinstance(value, bool) or not isinstance(value, (int, float))
            or not math.isfinite(value) or not 0 <= value <= 1):
        raise ValueError(f"{name} must be a finite probability in [0, 1]")


def selection_breakdown(attempts, on_target, p, q, s=.4, m=.25):
    count(attempts, "attempts")
    count(on_target, "on_target")
    if on_target > attempts:
        raise ValueError("on_target cannot exceed attempts")
    for name, value in {"p": p, "q": q, "s": s, "m": m}.items():
        probability(value, name)
    return {
        "attempts": attempts, "onTarget": on_target,
        "p": p, "q": q, "s": s, "m": m,
        "xgTotal": attempts * p,
        "xgotTotal": on_target * q,
        "selectedLift": on_target * (q-p),
        "excludedDebit": -(attempts-on_target)*p if attempts > on_target else 0,
        "totalLift": on_target*q-attempts*p,
        "targetContribution": (on_target-attempts*s)*m,
        "placementContribution": on_target*(q-m),
        "coherenceResidual": attempts*(s*m-p),
    }


def poisson_binomial_summary(probs, goals):
    if not isinstance(probs, (list, tuple)):
        raise TypeError("probs must be a list or tuple")
    count(goals, "goals")
    if goals > len(probs):
        raise ValueError("goals cannot exceed shot count")
    for index, p in enumerate(probs):
        probability(p, f"probs[{index}]")
    # Separate-array convolution is independent of the TypeScript in-place DP.
    mass = [1.0]
    for p in probs:
        nxt = [0.0] * (len(mass)+1)
        for k, value in enumerate(mass):
            nxt[k] += value*(1-p)
            nxt[k+1] += value*p
        mass = nxt
    expected = math.fsum(probs)
    variance = math.fsum(p*(1-p) for p in probs)
    lower_tail = (1.0 if goals == len(probs)
                  else min(1.0, max(0.0, math.fsum(mass[:goals+1]))))
    return {
        "n": len(probs), "expectedGoals": expected, "conceded": goals,
        "residual": expected-goals, "variance": variance,
        "sd": math.sqrt(variance), "lowerTail": lower_tail,
    }


def missing_residual_bounds(missing_goals, missing_non_goals):
    count(missing_goals, "missing_goals")
    count(missing_non_goals, "missing_non_goals")
    count(missing_goals+missing_non_goals, "total_missing")
    return {
        "lower": -missing_goals,
        "upper": missing_non_goals,
        "width": missing_goals+missing_non_goals,
    }


def height_audit():
    # Transcribed published aggregates, not individual player or shot records.
    # Chew et al. (2026), Data 11(11), 289; sections 2.3, 3.3, 3.7 and Table S5b.
    source = [
        ("Premier League", 3225, 1045, 2180, 3192, 33, 0, "0.0011", -.0091, .0011),
        ("Championship", 4583, 1443, 3140, 4532, 50, 1, "0.0096", -.0014, .0097),
        ("League One", 4428, 1462, 2966, 4390, 38, 0, "0.0058", -.0029, .0057),
    ]
    half_unit = Decimal("0.00005")
    rows = []
    lower_terms, upper_terms, residual_terms, rounding_terms = [], [], [], []
    for division, shots, goals, saves, valid, mg, mn, mean, lo, hi in source:
        if shots != goals+saves or shots != valid+mg+mn:
            raise ValueError("Published aggregate counts do not reconcile")
        residual = valid*Decimal(mean)
        rounding = valid*half_unit
        lower = residual-rounding-mg
        upper = residual+rounding+mn
        lower_terms.append(lower)
        upper_terms.append(upper)
        residual_terms.append(residual)
        rounding_terms.append(rounding)
        rows.append({
            "division": division, "shots": shots, "goals": goals,
            "saves": saves, "valid": valid, "missingGoals": mg,
            "missingNonGoals": mn, "reportedMean": float(mean),
            "publishedMeanBounds": {"lower": lo, "upper": hi},
            "observedResidualFromRoundedMean": float(residual),
            "roundingError": float(rounding),
            "fullResidualBounds": {"lower": float(lower), "upper": float(upper)},
            "fullMeanBounds": {"lower": float(lower/shots), "upper": float(upper/shots)},
        })
    shots = sum(row["shots"] for row in rows)
    goals = sum(row["goals"] for row in rows)
    missing_goals = sum(row["missingGoals"] for row in rows)
    missing_non_goals = sum(row["missingNonGoals"] for row in rows)
    lower, upper = sum(lower_terms), sum(upper_terms)
    return {
        "kind": "reported-aggregate-arithmetic",
        "sourceDoi": "10.3390/data11110289",
        "sourceUrl": "https://doi.org/10.3390/data11110289",
        "authors": "Chew, Ruiz-de-Alarcon-Quintero and De-la-Cruz-Torres (2026)",
        "roundingHalfUnit": float(half_unit),
        "credit": "The source authors already derive missing-probability bounds in Table S5b. This exercise pools published aggregates and propagates their four-decimal rounding; it does not replicate raw-shot analysis.",
        "rows": rows,
        "total": {
            "shots": shots, "goals": goals,
            "saves": sum(row["saves"] for row in rows),
            "valid": sum(row["valid"] for row in rows),
            "missingGoals": missing_goals,
            "missingNonGoals": missing_non_goals,
            "observedResidualFromRoundedMean": float(sum(residual_terms)),
            "roundingError": float(sum(rounding_terms)),
            "missingResidualBounds": missing_residual_bounds(missing_goals, missing_non_goals),
            "fullResidualBounds": {"lower": float(lower), "upper": float(upper)},
            "fullMeanBounds": {"lower": float(lower/shots), "upper": float(upper/shots)},
            "missingFraction": (missing_goals+missing_non_goals)/shots,
            "missingGoalFraction": missing_goals/goals,
        },
    }


def build_results():
    selection = [
        {"id": label, **selection_breakdown(100, k, .10, q)}
        for label, k, q in [("baseline", 40, .25), ("target", 50, .25),
                            ("placement", 40, .35), ("tradeoff", 30, .35)]
    ]
    aiming = [
        {"id": label, "onTargetRate": s, "quality": q, "expectedGoals": s*q}
        for label, s, q in [("central", .8, .2), ("corner", .5, .4), ("extreme", .25, .6)]
    ]
    uncertainty = []
    for label, groups in [
        ("uniform", [(100, .30)]), ("mixed", [(50, .05), (50, .55)])
    ]:
        probs = [p for n, p in groups for _ in range(n)]
        uncertainty.append({
            "id": label,
            "probabilityGroups": [{"count": n, "probability": p} for n, p in groups],
            **poisson_binomial_summary(probs, 20),
        })
    first, rebound, second = .4, .4, .5
    return {
        "schemaVersion": 1,
        "studyDate": "2026-11-30",
        "provenance": {
            "synthetic": "Constructed examples. No player measurements, empirical skill estimates or predictive performance claims.",
            "reportedAggregates": "Credited arithmetic on rounded published group means and counts. No access to raw licensed shots and no replication of the source models.",
            "numerics": "Deterministic calculations; exact distribution recurrence rather than Monte Carlo, subject to floating-point arithmetic. Published-aggregate rounding envelopes computed with Decimal.",
        },
        "selection": {
            "kind": "synthetic",
            "assumptions": "Same eligible attempt universe; Q=S*q. Missing q is not zero. Probability coherence additionally requires all goals to belong to S=1 and consistent conditional models.",
            "scenarios": selection,
        },
        "aiming": {
            "kind": "synthetic",
            "assumptions": "Scoring can occur only on target; expected goals per attempt equals on-target probability times conditional goal probability.",
            "scenarios": aiming,
        },
        "uncertainty": {
            "kind": "synthetic-independent-known-probability",
            "assumptions": "Independent Bernoulli outcomes with known fixed probabilities. Inclusive lower tails are not probabilities of goalkeeper skill and omit model uncertainty and dependence.",
            "scenarios": uncertainty,
        },
        "heightAudit": height_audit(),
        "rebound": {
            "kind": "synthetic",
            "assumptions": "A rebound occurs with the specified probability conditional on no first-shot goal. It is the only subsequent scoring opportunity in this toy model.",
            "first": first, "rebound": rebound, "second": second,
            "initialGoalProbability": first+(1-first)*rebound*second,
            "observedShotSum": first+second,
        },
        "supplementarySynthetic": {
            "kind": "synthetic",
            "outcomeAccounting": {
                "xg": 12, "xgot": 16, "goals": 18,
                "executionLift": 16-12, "outcomeResidual": 18-16,
                "goalsAbovePreShot": 18-12, "keeperResidual": 16-18,
            },
            "informationClock": {
                "preShotProbability": .10, "onTargetProbability": .40,
                "conditionalGoalProbability": .25,
                "preShotBrier": .10*(1-.10),
                "postShotBrier": .40*.25*(1-.25),
                "gain": .10*(1-.10)-.40*.25*(1-.25),
            },
            "shrinkage": {
                "assumptions": "All chances share reference probability .30. The illustrative Beta(30,70) prior is chosen, not fitted or recommended as universal.",
                "priorAlpha": 30, "priorBeta": 70,
                "keepers": [
                    {"shots": n, "goals": g,
                     "rawPreventionPerShot": .30-g/n,
                     "posteriorConcessionProbability": (30+g)/(100+n),
                     "posteriorPreventionPerShot": .30-(30+g)/(100+n)}
                    for n, g in [(20, 2), (100, 20)]
                ],
            },
            "reboundAlwaysOccursProbability": first+(1-first)*second,
        },
    }


def self_check(results):
    # Compare convolution to direct outcome enumeration, including probabilities 0/1.
    for probs in [[], [0], [1], [0, 1], [.2, .5, .8], [0, .1, .4, 1]]:
        for goals in range(len(probs)+1):
            direct = math.fsum(
                math.prod(p if outcome else 1-p for p, outcome in zip(probs, outcomes))
                for outcomes in itertools.product((0, 1), repeat=len(probs))
                if sum(outcomes) <= goals
            )
            assert math.isclose(poisson_binomial_summary(probs, goals)["lowerTail"], direct, abs_tol=1e-12)
    # Check the two large examples against binomial sums, not the DP recurrence.
    uniform = math.fsum(math.comb(100, k)*.3**k*.7**(100-k) for k in range(21))
    mixed = math.fsum(
        math.comb(50, i)*.05**i*.95**(50-i)
        *math.comb(50, j)*.55**j*.45**(50-j)
        for i in range(21) for j in range(21-i)
    )
    for scenario, expected in zip(results["uncertainty"]["scenarios"], [uniform, mixed]):
        assert math.isclose(scenario["lowerTail"], expected, abs_tol=1e-12)
    for n in range(13):
        for k in range(n+1):
            for p, q in itertools.product((0, .1, .75, 1), (0, .25, .8, 1)):
                row = selection_breakdown(n, k, p, q)
                assert math.isclose(row["totalLift"], row["selectedLift"]+row["excludedDebit"], abs_tol=1e-12)
                assert math.isclose(row["totalLift"], row["targetContribution"]+row["placementContribution"]+row["coherenceResidual"], abs_tol=1e-12)
    total = results["heightAudit"]["total"]
    assert total["shots"] == 12236 and total["valid"] == 12114
    assert total["missingResidualBounds"] == {"lower": -121, "upper": 1, "width": 122}
    assert total["fullResidualBounds"] == {"lower": -49.1253, "upper": 74.0861}


def compare_results(actual, expected, path="results"):
    if isinstance(expected, dict):
        if not isinstance(actual, dict) or actual.keys() != expected.keys():
            raise ValueError(f"{path}: object fields differ")
        for key in expected:
            compare_results(actual[key], expected[key], f"{path}.{key}")
    elif isinstance(expected, list):
        if not isinstance(actual, list) or len(actual) != len(expected):
            raise ValueError(f"{path}: list lengths differ")
        for i, (a, e) in enumerate(zip(actual, expected)):
            compare_results(a, e, f"{path}[{i}]")
    elif isinstance(expected, (int, float)) and not isinstance(expected, bool):
        if not isinstance(actual, (int, float)) or not math.isclose(actual, expected, rel_tol=1e-12, abs_tol=1e-12):
            raise ValueError(f"{path}: numeric values differ")
    elif actual != expected:
        raise ValueError(f"{path}: values differ")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    output = parser.add_mutually_exclusive_group()
    output.add_argument("--output", type=Path, help="Write JSON to this path instead of stdout")
    output.add_argument("--check", action="store_true", help="Check the adjacent results.json without modifying it")
    args = parser.parse_args()
    results = build_results()
    self_check(results)
    if args.check:
        saved = json.loads(Path(__file__).with_name("results.json").read_text(encoding="utf-8"))
        compare_results(saved, results)
        print("All deterministic scenarios and published-aggregate envelopes match results.json.")
        return
    serialized = json.dumps(results, indent=2, sort_keys=True, allow_nan=False)+"\n"
    if args.output:
        args.output.write_text(serialized, encoding="utf-8")
    else:
        sys.stdout.write(serialized)


if __name__ == "__main__":
    main()
