# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: StatsBomb open data, every competition-season with 26+ matches (43 seasons, 3,882 matches): events + lineups -> /tmp/sb
# Run xt_all.py (extract) then xt_rank.py (fit grids, rank players, write xt_seasons.json)

import json, glob, numpy as np, pandas as pd, sys
sys.path.insert(0, '/home/claude/cga')
from xt_all import fit, cell
data = pd.read_pickle('/tmp/sb/xt_all.pkl')
nick = {}
for f in glob.glob('/tmp/sb/lineups/*.json'):
    for tm in json.load(open(f)):
        for p in tm['lineup']: nick[p['player_id']] = p['player_nickname'] or p['player_name']
def pool(gender):
    ks = [k for k, d in data.items() if d['gender'] == gender and len(d['sh']) >= 3000]
    return fit(pd.concat([data[k]['mv'] for k in ks]), pd.concat([data[k]['sh'] for k in ks])), len(ks)
pooled = {g: pool(g) for g in ('male', 'female')}
out = []
for k, d in data.items():
    own = len(d['sh']) >= 3000
    xt = fit(d['mv'], d['sh']) if own else pooled[d['gender']][0]
    mv = d['mv'][d['mv'].ok].copy()
    mv['v'] = xt[cell(mv.ex, mv.ey)] - xt[cell(mv.x, mv.y)]
    g = mv.groupby(['pid', 'carry']).v.sum().unstack(fill_value=0).rename(columns={0: 'pass', 1: 'carry'})
    mi = d['mi'].groupby('pid').agg(mins=('mins', 'sum'), team=('team', lambda s: s.mode().iat[0]))
    g = g.join(mi, how='inner')
    thr = max(270, 0.4 * mi.mins.max())
    g = g[g.mins >= thr]
    for c in ('pass', 'carry'):
        if c not in g: g[c] = 0.0
    g['xt90'] = (g['pass'] + g['carry']) / g.mins * 90
    top = g.sort_values('xt90', ascending=False).head(15)
    season = d['season'].replace('/20', '/') if '/' in d['season'] else d['season']
    label = f"{d['comp']} {season}"
    note = (f"{d['focus']} matches only. " if d['focus'] else '') + (f"Grid fitted on this season's {len(d['sh']):,} open-play shots." if own else
            f"Small sample: grid pooled from {pooled[d['gender']][1]} large {'men' if d['gender']=='male' else 'women'}'s seasons.")
    grp = ('Women' if d['gender'] == 'female' else 'Men') + (' - leagues' if d['comp'] not in ('FIFA World Cup', 'UEFA Euro', 'Copa America', 'African Cup of Nations', "Women's World Cup", "UEFA Women's Euro") else ' - tournaments')
    out.append(dict(id=f"{k[0]}_{k[1]}", label=label, group=grp, n=d['n'], focus=d['focus'], note=note, thr=int(round(thr, -1)),
                    grid=[round(float(v), 4) for v in xt], gmax=round(float(xt.max()), 4),
                    players=[dict(name=nick.get(pid, str(pid)), team=r.team, mins=int(r.mins), xt90=round(r.xt90, 3), p90=round(r['pass'] / r.mins * 90, 3), c90=round(r.carry / r.mins * 90, 3)) for pid, r in top.iterrows()]))
def skey(o):
    s = o['label'].split()[-1]; return (o['group'], o['label'].rsplit(' ', 1)[0], s)
out.sort(key=skey)
json.dump(out, open('/tmp/sb/xt_seasons.json', 'w'), ensure_ascii=False, separators=(',', ':'))
for o in out: print(f"{o['label']:36} {o['n']:4} thr {o['thr']:5}  1. {o['players'][0]['name']} ({o['players'][0]['xt90']:.2f})  2. {o['players'][1]['name']}")
print(len(out), 'seasons; json KB', round(len(json.dumps(out)) / 1024))
