#!/usr/bin/env python3
"""Historical geometry-only xG replication; see empirical-protocol.md.

Requires Python 3.11+, numpy, scipy and scikit-learn. All features use shot origins.
Run: python empirical.py --data-dir data --output empirical-results.json
Use --download to retrieve immutable CC BY 4.0 source files from Figshare.
Data attribution: Pappalardo et al. (2019), Scientific Data 6:236,
https://doi.org/10.1038/s41597-019-0247-7; Wyscout event collection,
https://doi.org/10.6084/m9.figshare.c.4415000; CC BY 4.0.
"""
import argparse
import collections
import csv
import hashlib
import json
import math
from pathlib import Path
import platform
import urllib.request
import zipfile

import numpy as np
import scipy
from scipy.optimize import brentq
from scipy.special import expit, logit
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

FILES = {
    'events.zip': (14464685, '7c20e8647e7eda58d7838a0c7b1ec6ab', 'events_England.json'),
    'matches.zip': (14464622, '51d80beb17480919f69a53a0152c2d71', 'matches_England.json'),
}


def prepare(data_dir, download):
    data_dir.mkdir(exist_ok=True, parents=True)
    provenance = []
    for filename, (fid, expected_md5, extracted) in FILES.items():
        path = data_dir / filename
        if not path.exists():
            if not download:
                raise FileNotFoundError(f'{path}; add --download to retrieve official source')
            with urllib.request.urlopen(f'https://ndownloader.figshare.com/files/{fid}', timeout=60) as r, path.open('wb') as out:
                while chunk := r.read(1024*1024):
                    out.write(chunk)
        data = path.read_bytes()
        observed_md5 = hashlib.md5(data).hexdigest()
        if observed_md5 != expected_md5:
            raise ValueError(f'Source MD5 mismatch for {filename}: {observed_md5}')
        with zipfile.ZipFile(path) as z:
            payload = z.read(extracted)
            (data_dir / extracted).write_bytes(payload)
        provenance.append(dict(name=filename, file_id=fid,
            download_url=f'https://ndownloader.figshare.com/files/{fid}',
            md5=observed_md5, sha256=hashlib.sha256(data).hexdigest(),
            bytes=len(data), extracted_name=extracted,
            extracted_sha256=hashlib.sha256(payload).hexdigest(),
            extracted_bytes=len(payload)))
    return provenance


def losses(y, p):
    p = np.clip(p, 1e-12, 1-1e-12)
    return (p-y)**2, -(y*np.log(p)+(1-y)*np.log1p(-p))


def ci(values):
    return np.quantile(values, [.025, .975]).tolist()


def main(data_dir, output, download):
    provenance = prepare(data_dir, download)
    matches = sorted(json.loads((data_dir/'matches_England.json').read_text()), key=lambda m:(m['dateutc'], m['wyId']))
    assert len(matches)==380
    lookup = {m['wyId']:m for m in matches}
    first_cut = matches[math.floor(.6*len(matches))-1]['dateutc'][:10]
    second_cut = matches[math.floor(.8*len(matches))-1]['dateutc'][:10]
    partition = lambda date: 'train' if date[:10]<=first_cut else 'calibration' if date[:10]<=second_cut else 'test'
    match_groups = collections.defaultdict(list)
    for m in matches:
        match_groups[partition(m['dateutc'])].append(m)
    events = json.loads((data_dir/'events_England.json').read_text())
    counts = collections.Counter()
    rows = []
    for e in events:
        counts['all_events']+=1
        if e['eventId']!=10 or e['subEventId']!=100:
            counts['not_ordinary_shot']+=1
            continue
        counts['ordinary_shot_records']+=1
        if e['matchPeriod'] not in ('1H','2H'):
            counts['excluded_period']+=1
            continue
        tags = {x['id'] for x in e.get('tags',[])}
        if 102 in tags:
            counts['excluded_own_goal']+=1
            continue
        pos = e.get('positions', [])
        if not pos or 'x' not in pos[0] or 'y' not in pos[0]:
            counts['excluded_missing_position']+=1
            continue
        x, y = float(pos[0]['x']), float(pos[0]['y'])
        if not(math.isfinite(x) and math.isfinite(y) and 0<=x<=100 and 0<=y<=100):
            counts['excluded_invalid_position']+=1
            continue
        dx = (100-x)*1.05
        dy = (y-50)*.68
        distance = math.hypot(dx,dy)
        angle = math.atan2(7.32*dx, dx*dx+dy*dy-(7.32/2)**2)
        # atan2 returns [0,pi] for dx>=0; singular exact-post locations are excluded.
        if dx==0 and abs(abs(dy)-3.66)<1e-12:
            counts['excluded_singular_position']+=1
            continue
        m = lookup[e['matchId']]
        rows.append(dict(event_id=e['id'], match_id=e['matchId'], team_id=e['teamId'],
            dateutc=m['dateutc'], split=partition(m['dateutc']),
            distance=distance, angle=angle, goal=int(101 in tags)))
    del events
    rows.sort(key=lambda e:(e['dateutc'],e['match_id'],e['event_id']))
    counts['included_shots']=len(rows)
    sets = {k:[r for r in rows if r['split']==k] for k in ('train','calibration','test')}
    arrays = {k:(np.array([[r['distance'],r['angle']] for r in v]),np.array([r['goal'] for r in v])) for k,v in sets.items()}
    scaler = StandardScaler().fit(arrays['train'][0])
    model = LogisticRegression(C=1., solver='lbfgs', max_iter=1000, tol=1e-10).fit(scaler.transform(arrays['train'][0]), arrays['train'][1])
    constant = float(arrays['train'][1].mean())
    p_cal = model.predict_proba(scaler.transform(arrays['calibration'][0]))[:,1]
    delta = brentq(lambda d: np.sum(expit(logit(p_cal)+d)-arrays['calibration'][1]),-20,20)
    p_test = model.predict_proba(scaler.transform(arrays['test'][0]))[:,1]
    y_test = arrays['test'][1]
    predictions = dict(constant=np.full(len(y_test),constant), geometry=p_test, geometry_recalibrated=expit(logit(p_test)+delta))
    match_ids = [m['wyId'] for m in match_groups['test']]
    mids = np.array([r['match_id'] for r in sets['test']])
    match_idx = {m:np.flatnonzero(mids==m) for m in match_ids}
    assert all(len(v)>0 for v in match_idx.values())
    cluster_n = np.array([len(match_idx[m]) for m in match_ids])
    rng=np.random.default_rng(20261201)
    bootstrap_indices=rng.integers(0,len(match_ids),size=(2000,len(match_ids)))
    bootstrap_n=cluster_n[bootstrap_indices].sum(axis=1)
    model_results={}
    bootstrap_scores={}
    all_losses={}
    bins=np.array([0,.05,.10,.20,.30,.50,1.])
    for name,p in predictions.items():
        b,ll=losses(y_test,p)
        all_losses[name]={'brier':b,'log_loss':ll}
        bootstrap_scores[name]={}
        metrics={}
        for label,values in [('brier',b),('log_loss',ll)]:
            cluster_sum=np.array([values[match_idx[m]].sum() for m in match_ids])
            boot=cluster_sum[bootstrap_indices].sum(axis=1)/bootstrap_n
            bootstrap_scores[name][label]=boot
            metrics[label]=dict(value=float(values.mean()),ci95=ci(boot))
        bin_rows=[]
        for lo,hi in zip(bins[:-1],bins[1:]):
            mask=(p>=lo)&(p<hi if hi<1 else p<=hi)
            n=int(mask.sum())
            bin_rows.append(dict(lower=float(lo),upper=float(hi),n=n,
                mean_probability=float(p[mask].mean()) if n else None,
                goal_fraction=float(y_test[mask].mean()) if n else None,
                goals=int(y_test[mask].sum())))
        model_results[name]=dict(**metrics,sum_probabilities=float(p.sum()),mean_probability=float(p.mean()),calibration_bins=bin_rows)
    paired={}
    for name,baseline in [('geometry','constant'),('geometry_recalibrated','constant'),('geometry_recalibrated','geometry')]:
        paired[f'{name}_minus_{baseline}']={}
        for metric in ['brier','log_loss']:
            paired[f'{name}_minus_{baseline}'][metric]=dict(
                value=float((all_losses[name][metric]-all_losses[baseline][metric]).mean()),
                ci95=ci(bootstrap_scores[name][metric]-bootstrap_scores[baseline][metric]))
    # Publish compact derived match aggregates for independent paired-score checks.
    summary_path=output.with_name('empirical-match-summary.csv')
    with summary_path.open('w', newline='') as out:
        fields=['match_id','dateutc','shots','goals']+[f'{name}_{quantity}' for name in predictions for quantity in ['probability_sum','brier_sum','log_loss_sum']]
        writer=csv.DictWriter(out,fieldnames=fields);writer.writeheader()
        for mid in match_ids:
            idx=match_idx[mid]
            row=dict(match_id=mid,dateutc=lookup[mid]['dateutc'],shots=len(idx),goals=int(y_test[idx].sum()))
            for name,p in predictions.items():
                row[f'{name}_probability_sum']=float(p[idx].sum())
                row[f'{name}_brier_sum']=float(all_losses[name]['brier'][idx].sum())
                row[f'{name}_log_loss_sum']=float(all_losses[name]['log_loss'][idx].sum())
            writer.writerow(row)
    splits={}
    for name, ms in match_groups.items():
        ys=arrays[name][1]
        splits[name]=dict(matches=len(ms),shots=len(ys),goals=int(ys.sum()),goal_fraction=float(ys.mean()),
                         from_utc=ms[0]['dateutc'],through_utc=ms[-1]['dateutc'],match_ids=[m['wyId'] for m in ms])
    # Descriptive fixed-shot-list compression gap using the raw fitted geometry model.
    # This is not a match probability validation; shot lists are selected after kickoff.
    team_match=collections.defaultdict(list)
    for row,p in zip(sets['test'],p_test):team_match[(row['match_id'],row['team_id'])].append(float(p))
    gaps=[]
    for key,ps in team_match.items():
        mu=sum(ps)
        gaps.append((-math.expm1(sum(math.log1p(-p) for p in ps)))-(-math.expm1(-mu)))
    result=dict(
        protocol='CRJ-XG-20261201-EMPIRICAL-v1',study_type='historical chronological shot-level replication',
        created='2026-12-01',dataset='Wyscout English first division 2017/18',
        data_source='https://doi.org/10.6084/m9.figshare.c.4415000',
        source_article='https://doi.org/10.1038/s41597-019-0247-7',
        attribution='Pappalardo et al. (2019); data collected by Wyscout; CC BY 4.0. Cateo analysis and modifications; no endorsement implied.',
        license='https://creativecommons.org/licenses/by/4.0/',provenance=provenance,
        population='Recorded ordinary shots eventId=10, subEventId=100, 1H/2H, valid origin, no own-goal tag102. Penalties and direct free kicks excluded by event code.',
        target='Goal tag101 on the same shot; not full-match goals or pre-match probability.',
        exclusions=dict(counts),splits=splits,
        features=['distance_m','angle_radians'],pitch_assumption=dict(length_m=105,width_m=68,goal_width_m=7.32),
        fit=dict(C=1.,solver='lbfgs',max_iter=1000,tol=1e-10,train_only_scaler_mean=scaler.mean_.tolist(),
                 train_only_scaler_scale=scaler.scale_.tolist(),standardized_coefficients=model.coef_[0].tolist(),
                 intercept=float(model.intercept_[0]),iterations=model.n_iter_.tolist(),constant_probability=constant,
                 calibration_intercept_shift=float(delta)),
        test_metrics=model_results,paired_differences=paired,
        bootstrap=dict(seed=20261201,replicates=2000,unit='match',sample_matches=len(match_ids),interval='percentile 95%',weighting='shot weighted; resample complete matches'),
        descriptive_compression_gap=dict(team_matches=len(gaps),mean=float(np.mean(gaps)),median=float(np.median(gaps)),
            percentile_10_90=np.quantile(gaps,[.1,.9]).tolist(),note='At-least-one probability under a fixed independent shot list minus mean-matched Poisson. Not tested as a prospective match forecast.'),
        software=dict(python=platform.python_version(),numpy=np.__version__,scipy=scipy.__version__,sklearn=sklearn.__version__),
        limitations=['One historical league-season and a single final time block; no tuning on final outcomes.',
                     'Whole-match bootstrap conditions on fitted models; cross-match team dependence and training uncertainty are not included.',
                     'Coarse shot origins, assumed pitch size, no defenders, goalkeeper, shot type, player ability, score state or trajectory.',
                     'Shot selection and future shot availability make this unsuitable as direct pre-match forecast evidence.',
                     'This is a Cateo-built minimal baseline, not validation of any commercial xG provider or Cateo production forecast model.',
                     'The temporal split does not establish contemporaneous 2018 data availability; the public dataset was retrieved in 2026.'])
    output.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({k:result[k] for k in ['exclusions','splits','test_metrics','paired_differences','descriptive_compression_gap']},indent=2))


if __name__=='__main__':
    ap=argparse.ArgumentParser()
    ap.add_argument('--data-dir',type=Path,default=Path('data'))
    ap.add_argument('--output',type=Path,default=Path('empirical-results.json'))
    ap.add_argument('--download',action='store_true')
    a=ap.parse_args()
    main(a.data_dir,a.output,a.download)
