#!/usr/bin/env python3
"""Cateo Research Journal: exact xG aggregation experiments, 2026-12-01.

Python >=3.9, standard library only. Run: python reproduce.py --output results.json
These are specified probability experiments, not estimates from football data.
No random numbers are used; a seed or sampling confidence interval is inapplicable.
The elementary identities are established prior art, not new statistical methods.
"""

import argparse
from fractions import Fraction as F
import json
import math
from pathlib import Path


def pb(probs):
    """Exact independent Bernoulli convolution, rational arithmetic."""
    a = [F(1)]
    for p in probs:
        p = F(p)
        b = [F(0)] * (len(a) + 1)
        for i, mass in enumerate(a):
            b[i] += mass * (1 - p)
            b[i + 1] += mass * p
        a = b
    assert sum(a) == 1
    return a


def describe(a):
    mean = sum(i * p for i, p in enumerate(a))
    variance = sum((i - mean) ** 2 * p for i, p in enumerate(a))
    return dict(pmf=a, mean=mean, variance=variance,
                at_least_one=1-a[0], at_least_two=sum(a[2:]),at_least_three=sum(a[3:]))


def outcome(a, b):
    win = sum(p * q for i, p in enumerate(a) for j, q in enumerate(b) if i > j)
    draw = sum(p * q for i, p in enumerate(a) for j, q in enumerate(b) if i == j)
    loss = sum(p * q for i, p in enumerate(a) for j, q in enumerate(b) if i < j)
    return dict(win=win, draw=draw, loss=loss, represented_mass=win+draw+loss)


def poisson(mu, maximum=60):
    a = [math.exp(-mu)]
    for i in range(1, maximum + 1):
        a.append(a[-1] * mu / i)
    return a


def exact_fraction_strings(value):
    if isinstance(value, F):
        return str(value)
    if isinstance(value, dict):
        return {k: exact_fraction_strings(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [exact_fraction_strings(v) for v in value]
    return value


def numeric(value):
    if isinstance(value, F):
        return float(value)
    if isinstance(value, dict):
        return {k: numeric(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [numeric(v) for v in value]
    return value


def run():
    opponent = [F(3, 10)] * 4
    opponent_pmf = pb(opponent)
    profiles = []
    for label, shots in [('concentrated', [F(3,5)]*2),
                         ('diffuse', [F(1,10)]*12),
                         ('opponent', opponent)]:
        dist = pb(shots)
        row = dict(name=label, shots=shots, **describe(dist))
        row['xg_total'] = sum(shots)
        row['second_moment_sum'] = sum(p*p for p in shots)
        row['concentration_hhi'] = sum(p*p for p in shots) / sum(shots)**2
        row['zero_event_equivalent_rate'] = -sum(math.log1p(-float(p)) for p in shots)
        row['vs_fixed_opponent'] = outcome(dist, opponent_pmf)
        profiles.append(row)
    assert profiles[0]['xg_total'] == profiles[1]['xg_total'] == F(6,5)
    assert profiles[0]['at_least_one'] == F(21,25)

    poisson_pmf = poisson(1.2)
    fixed_lists = dict(
        question='What is lost when different fixed independent shot lists are compressed to the same xG total?',
        assumption='Condition on specified exogenous shot lists; all shot outcomes and both teams are independent.',
        profiles=profiles,
        poisson_mean_matched=dict(mean=1.2, variance=1.2,
            at_least_one=-math.expm1(-1.2),
            at_least_two=1-math.exp(-1.2)*2.2,
            at_least_three=1-math.exp(-1.2)*(1+1.2+1.2**2/2),
            pmf=poisson_pmf,
            versus_same_poisson=outcome(poisson_pmf, poisson_pmf),
            versus_fixed_opponent=outcome(poisson_pmf, opponent_pmf)),
        limitation='A realized football shot list is outcome-dependent. These are conditional reference distributions, not a causal replay or a pre-match forecast.'
    )

    p, r, q = F(2,5), F(1,2), F(3,5)
    leaves = [
        dict(path='first_goal', probability=p, goals=1, realized_xg=p),
        dict(path='first_miss_no_rebound', probability=(1-p)*(1-r), goals=0, realized_xg=p),
        dict(path='first_miss_rebound_goal', probability=(1-p)*r*q, goals=1, realized_xg=p+q),
        dict(path='first_miss_rebound_miss', probability=(1-p)*r*(1-q), goals=0, realized_xg=p+q),
    ]
    actual_goals = sum(row['probability'] * row['goals'] for row in leaves)
    actual_xg = sum(row['probability'] * row['realized_xg'] for row in leaves)
    assert actual_goals == actual_xg == F(29,50)
    assert sum(row['probability'] for row in leaves) == 1
    rebound = dict(
        first_shot_probability=p, rebound_arrival_given_first_miss=r,
        rebound_conversion_given_arrival=q, leaves=leaves,
        pre_possession_probability_of_a_goal=actual_goals,
        expected_sum_realized_shot_xg=actual_xg,
        realized_xg_sum_on_rebound_path=p+q,
        goal_probability_given_rebound_occurs=q,
        fixed_two_shot_independent_probability=1-(1-p)*(1-q),
        limitation='The fixed-list, pre-possession, and selected realized-path quantities condition on different information. Linear expectation is not violated.'
    )

    high, low = pb([F(1,2)]*2), pb([F(1,10)]*2)
    mixed = [(a+b)/2 for a,b in zip(high, low)]
    independent = pb([F(3,10)]*2)
    dependent = dict(
        latent_high_probability=F(1,2),
        per_shot_high=F(1,2), per_shot_low=F(1,10),
        marginal_per_shot_probability=F(3,10),
        covariance=F(1,25),
        mixture=describe(mixed), independent=describe(independent),
        limitation='Shots are conditionally independent within the latent regime but dependent after the regime is marginalized. Marginally correct xG does not identify joint scoring probabilities.'
    )
    assert dependent['mixture']['mean'] == dependent['independent']['mean'] == F(3,5)
    assert dependent['mixture']['variance'] == F(1,2)

    q_one, seconds = F(1,50), 5
    rate_rows = []
    for hz in [1, 5, 10, 25, 50]:
        dt = 1/hz
        frames = seconds*hz
        q_frame = -math.expm1(math.log1p(-float(q_one))*dt)
        corrected = -math.expm1(frames*math.log1p(-q_frame))
        repeated = 1-(1-q_one)**frames
        rate_rows.append(dict(hertz=hz, timestep_seconds=dt, intervals=frames,
                              naive_repeated_probability=repeated,
                              constant_hazard_probability_per_interval=q_frame,
                              corrected_probability=corrected))
    invariant = 1-(1-q_one)**seconds
    for row in rate_rows:
        assert abs(row['corrected_probability']-float(invariant)) < 1e-14
    time_resolution = dict(
        one_second_probability=q_one, duration_seconds=seconds,
        one_second_interpretation='A conditional probability on one nonoverlapping one-second interval under an assumed constant hazard.',
        exact_probability_over_duration=invariant,
        rows=rate_rows,
        limitation='Successive next-second classifier predictions usually have overlapping outcome windows. Multiplying their complements is not a valid survival model without an explicit interval/hazard interpretation; the conversion here is justified only by the specified constant-hazard toy model.'
    )

    # Extra robustness example: global calibration can hide domain/context errors.
    groups = [F(1,20), F(7,20)]
    pooled = sum(groups)/2
    oracle_brier = sum(q*(1-q) for q in groups)/2
    pooled_brier = pooled*(1-pooled)
    H = lambda q: -float(q)*math.log(float(q))-(1-float(q))*math.log1p(-float(q))
    calibration = dict(
        equal_group_true_probabilities=groups, constant_forecast=pooled,
        pooled_forecast_perfectly_calibrated_overall=True,
        pooled_forecast_expected_brier=pooled_brier,
        context_aware_expected_brier=oracle_brier,
        expected_brier_improvement=pooled_brier-oracle_brier,
        pooled_forecast_expected_log_loss=H(pooled),
        context_aware_expected_log_loss=sum(H(q) for q in groups)/2,
        limitation='Oracle probabilities are stipulated, not fitted. This is an identification example, not evidence that an actual model can discover the groups.'
    )

    body = dict(
        protocol='CRJ-XG-20261201-v1', study_type='exact synthetic methodological experiments',
        date='2026-12-01', empirical_football_matches=0,
        computation='Rational arithmetic for finite Bernoulli examples; IEEE float64 for logs/exponentials and Poisson tails. No stochastic simulation.',
        seed=None, uncertainty='No sampling confidence intervals: inputs are specified, not estimated. Real-world model and structural uncertainty remain unquantified.',
        fixed_lists=fixed_lists, rebound_tree=rebound,
        latent_dependence=dependent, time_resolution=time_resolution,
        supplementary_global_calibration=calibration,
        prior_art=[
            dict(url='https://www.mdpi.com/1099-4300/28/5/527', scope='Poisson-binomial concentration and zero-event-equivalent rate; formulas are established prior art.'),
            dict(url='https://arxiv.org/abs/2512.00203', scope='Possession-aware modeling with shot occurrence and conversion; unrefereed preprint.'),
            dict(url='https://wsb.wharton.upenn.edu/beyond-expected-goals/', scope='Institutional research note on possession-aware xG; its xG+ notation differs from the Entropy article.')
        ]
    )
    return dict(**numeric(body), exact_rational_results=exact_fraction_strings(dict(
        fixed_profiles=profiles, rebound_tree=rebound, latent_dependence=dependent,
        duration_probability=invariant, supplementary_global_calibration=calibration)))


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('--output', default='results.json')
    args = ap.parse_args()
    result = run()
    Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
    print(json.dumps({k: result[k] for k in ['protocol','study_type','empirical_football_matches']}, indent=2))
