# 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)

# Expected threat (xT) for every StatsBomb open-data season with 26+ matches
import json, glob, numpy as np, pandas as pd
from concurrent.futures import ProcessPoolExecutor
NX, NY = 16, 12; N = NX * NY
SETP = {'Corner', 'Free Kick', 'Throw-in', 'Goal Kick', 'Kick Off'}
def cell(x, y):
    return np.clip((np.asarray(x) / 120 * NX).astype(int), 0, NX - 1) * NY + np.clip((np.asarray(y) / 80 * NY).astype(int), 0, NY - 1)
def one(mid):
    try:
        ev = json.load(open(f'/tmp/sb/events/{mid}.json'))
    except Exception:
        return None
    mv, sh, mins = [], [], {}
    end = max((e['minute'] for e in ev), default=90)
    for e in ev:
        t = e['type']['name']
        if t == 'Starting XI':
            for p in e['tactics']['lineup']:
                mins[p['player']['id']] = [e['team']['name'], 0, end]
        elif t == 'Substitution':
            if e['player']['id'] in mins: mins[e['player']['id']][2] = e['minute']
            mins[e['substitution']['replacement']['id']] = [e['team']['name'], e['minute'], end]
        elif t in ('Bad Behaviour', 'Foul Committed'):
            card = (e.get('bad_behaviour') or e.get('foul_committed') or {}).get('card', {}).get('name')
            if card in ('Red Card', 'Second Yellow') and e.get('player') and e['player']['id'] in mins: mins[e['player']['id']][2] = e['minute']
        elif t == 'Pass' and e['pass'].get('type', {}).get('name') not in SETP and 'location' in e:
            el = e['pass'].get('end_location')
            mv.append((e['player']['id'], e['team']['name'], 0, e['location'][0], e['location'][1], el[0], el[1], 'outcome' not in e['pass']))
        elif t == 'Carry' and 'location' in e:
            el = e['carry']['end_location']
            mv.append((e['player']['id'], e['team']['name'], 1, e['location'][0], e['location'][1], el[0], el[1], True))
        elif t == 'Shot' and e['shot']['type']['name'] == 'Open Play':
            sh.append((e['location'][0], e['location'][1], e['shot']['outcome']['name'] == 'Goal'))
    return mid, mv, sh, [(pid, v[0], v[2] - v[1]) for pid, v in mins.items()]
def fit(mv, sh):
    s_c = np.bincount(cell(sh.x, sh.y), minlength=N); g_c = np.bincount(cell(sh.x, sh.y), weights=sh.goal.astype(float), minlength=N)
    m_c = np.bincount(cell(mv.x, mv.y), minlength=N); tot = s_c + m_c
    ps = np.divide(s_c, tot, out=np.zeros(N), where=tot > 0); pm = np.divide(m_c, tot, out=np.zeros(N), where=tot > 0)
    pg = np.divide(g_c, s_c, out=np.zeros(N), where=s_c > 0)
    ok = mv[mv.ok]; T = np.zeros((N, N)); np.add.at(T, (cell(ok.x, ok.y), cell(ok.ex, ok.ey)), 1)
    T = np.divide(T, m_c[:, None], out=np.zeros_like(T), where=m_c[:, None] > 0)
    xt = np.zeros(N)
    for _ in range(30): xt = ps * pg + pm * (T @ xt)
    return xt
if __name__ == '__main__':
    keep = json.load(open('/tmp/sb/keep.json'))
    comps = {(c['competition_id'], c['season_id']): c for c in json.load(open('/tmp/sb/comps.json'))}
    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']
    data = {}
    with ProcessPoolExecutor(8) as ex:
        for cid, sid, n in keep:
            ms = json.load(open(f'/tmp/sb/matches_{cid}_{sid}.json')); ids = [m['match_id'] for m in ms]
            MV, SH, MI = [], [], []
            for r in ex.map(one, ids, chunksize=4):
                if not r: continue
                mid, mv, sh, mi = r; MV += mv; SH += sh; MI += mi
            mv = pd.DataFrame(MV, columns=['pid', 'team', 'carry', 'x', 'y', 'ex', 'ey', 'ok']); sh = pd.DataFrame(SH, columns=['x', 'y', 'goal'])
            mi = pd.DataFrame(MI, columns=['pid', 'team', 'mins'])
            teams = pd.Series([t for m in ms for t in (m['home_team']['home_team_name'], m['away_team']['away_team_name'])]).value_counts()
            focus = teams.index[0] if teams.iloc[0] >= .9 * len(ms) and len(teams) > 3 and teams.iloc[0] > teams.iloc[1] * 2 else None
            c = comps[(int(cid), int(sid))]
            data[(cid, sid)] = dict(mv=mv, sh=sh, mi=mi, n=len(ms), comp=c['competition_name'], season=c['season_name'], gender=c['competition_gender'], focus=focus)
            print(c['competition_name'], c['season_name'], len(ms), len(mv), len(sh), 'focus:', focus, flush=True)
    pd.to_pickle(data, '/tmp/sb/xt_all.pkl')
