# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: Impect open data, Bundesliga 2023/24 (github.com/ImpectAPI/open-data): player_kpis, squads, players -> /tmp/imp

# Packing with Impect's own data: Bundesliga 2023/24 (306 matches) - does the team that bypasses more opponents win?
import json, glob, pandas as pd, numpy as np
sq = {s['id']: s['name'] for s in json.load(open('/tmp/imp/squads_743.json'))}
pl = {p['id']: p.get('commonname') or f"{p.get('firstname','')} {p.get('lastname','')}".strip() for p in json.load(open('/tmp/imp/players_743.json'))}
rows, prow = [], []
for f in glob.glob('/tmp/imp/pk/*.json'):
    d = json.load(open(f)); mid = d['matchId']
    side = {}
    for k in ('squadHome', 'squadAway'):
        s = d[k]; tot = dict(byp=0, byd=0, goals=0, og=0, xg=0)
        for p in s['players']:
            kv = {x['kpiId']: x['value'] for x in p['kpis']}
            tot['byp'] += kv.get(0, 0); tot['byd'] += kv.get(2, 0); tot['goals'] += kv.get(28, 0); tot['og'] += kv.get(38, 0); tot['xg'] += kv.get(82, 0)
            prow.append((mid, s['id'], p['id'], p['position'], p['playDuration'] / 60, kv.get(0, 0), kv.get(2, 0), kv.get(7, 0)))
        side[k] = (s['id'], tot)
    (h, th), (a, ta) = side['squadHome'], side['squadAway']
    hg, ag = th['goals'] + ta['og'], ta['goals'] + th['og']
    rows.append((mid, sq[h], sq[a], hg, ag, th['byp'], ta['byp'], th['byd'], ta['byd'], th['xg'], ta['xg']))
m = pd.DataFrame(rows, columns=['mid', 'home', 'away', 'hg', 'ag', 'hbyp', 'abyp', 'hbyd', 'abyd', 'hxg', 'axg'])
def res(r, a, b):
    if r.hg == r.ag: return 'draw'
    return 'more' if (r.hg > r.ag) == (r[a] > r[b]) else 'fewer'
for k, (a, b) in {'opponents': ('hbyp', 'abyp'), 'defenders': ('hbyd', 'abyd')}.items():
    m['res_' + k] = m.apply(lambda r: res(r, a, b), axis=1)
    v = m['res_' + k].value_counts(normalize=True); dec = m[m['res_' + k] != 'draw']
    print(k, 'won', round(v.get('more', 0), 3), 'drew', round(v.get('draw', 0), 3), 'lost', round(v.get('fewer', 0), 3), '| of decided:', round((dec['res_' + k] == 'more').mean(), 3), len(dec))
# xG comparison benchmark
m['res_xg'] = m.apply(lambda r: res(r, 'hxg', 'axg'), axis=1); dec = m[m.res_xg != 'draw']; print('xG of decided', round((dec.res_xg == 'more').mean(), 3))
# team season table
t = []
for _, r in m.iterrows():
    for tm, o, gf, ga, b, bd in ((r.home, r.away, r.hg, r.ag, r.hbyp, r.hbyd), (r.away, r.home, r.ag, r.hg, r.abyp, r.abyd)):
        t.append((tm, 3 if gf > ga else 1 if gf == ga else 0, b, bd, gf - ga))
T = pd.DataFrame(t, columns=['team', 'pts', 'byp', 'byd', 'gd']).groupby('team').agg(pts=('pts', 'sum'), byp=('byp', 'mean'), byd=('byd', 'mean'), gd=('gd', 'sum')).sort_values('pts', ascending=False)
print(T.round(1)); print('corr byp~pts', round(T.byp.corr(T.pts), 2), ' byd~pts', round(T.byd.corr(T.pts), 2))
P = pd.DataFrame(prow, columns=['mid', 'sq', 'pid', 'pos', 'mins', 'byp', 'byd', 'byp_rec'])
P = P.groupby(['pid', 'sq']).agg(mins=('mins', 'sum'), byp=('byp', 'sum'), byd=('byd', 'sum'), byp_rec=('byp_rec', 'sum'), pos=('pos', lambda s: s.mode().iat[0])).reset_index()
P = P[P.mins >= 1200]; P['byp90'] = P.byp / P.mins * 90; P['rec90'] = P.byp_rec / P.mins * 90
P['name'] = P.pid.map(pl); P['team'] = P.sq.map(sq)
print(P.sort_values('byp90', ascending=False).head(10)[['name', 'team', 'pos', 'byp90', 'rec90']].round(1).to_string())
print(P.sort_values('rec90', ascending=False).head(8)[['name', 'team', 'pos', 'rec90']].round(1).to_string())
m.to_csv('/tmp/imp/matches_res.csv', index=False); T.to_csv('/tmp/imp/teams.csv'); P.to_csv('/tmp/imp/players.csv', index=False)
