# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: StatsBomb open data, Premier League 2015/16 (competition 2, season 27): github.com/statsbomb/open-data
# Order: download events to /tmp/sb/events, run flatten.py, base.py, then a1 (needed by a8), a2, a3, a5, a6, a8

import json, pandas as pd, numpy as np
ev = pd.read_parquet('/tmp/sb/epl1516.parquet')
M = json.load(open('/tmp/sb/epl_matches.json'))
matches = pd.DataFrame([dict(match_id=m['match_id'], date=m['match_date'], home=m['home_team']['home_team_name'], away=m['away_team']['away_team_name'],
                             hs=m['home_score'], as_=m['away_score']) for m in M])
def minutes():
    end = ev.groupby(['match_id','period']).minute.max().groupby('match_id').max().rename('end')
    rows=[]
    for (mid,team),g in ev[ev.type.isin(['Starting XI','Substitution','Bad Behaviour','Foul Committed'])].groupby(['match_id','team']):
        e=end[mid]; on={}; off={}
        for _,r in g.iterrows():
            if r.type=='Starting XI':
                for p in r.lineup.split('|'): on[p]=0
            elif r.type=='Substitution':
                off[r.player]=r.minute; on[r.recipient]=r.minute
            elif r.card in ('Red Card','Second Yellow'):
                off[r.player]=r.minute
        for p,s in on.items(): rows.append((mid,team,p,s,off.get(p,e)))
    return pd.DataFrame(rows,columns=['match_id','team','player','on','off'])
if __name__=='__main__':
    mins=minutes(); mins['mins']=mins.off-mins.on; mins.to_parquet('/tmp/sb/mins.parquet'); matches.to_parquet('/tmp/sb/matches.parquet')
    print(mins.groupby('player').mins.sum().sort_values().tail(5)); print(matches.head(3)); print(len(matches))
