# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: StatsBomb open data events + three-sixty for Euro 2020 (55/43), World Cup 2022 (43/106), Euro 2024 (55/282) -> /tmp/s360

# Packing from StatsBomb 360 freeze frames (Euro 2020, World Cup 2022, Euro 2024)
import json, glob, numpy as np, pandas as pd
from concurrent.futures import ProcessPoolExecutor
def tri_count(sx,sy,pts):
    # opponents inside triangle ball -> posts (120,36),(120,44)
    ax,ay,bx,by,cx,cy=sx,sy,120,36,120,44
    n=0
    for px,py in pts:
        d=(by-cy)*(ax-cx)+(cx-bx)*(ay-cy)
        if d==0: continue
        l1=((by-cy)*(px-cx)+(cx-bx)*(py-cy))/d; l2=((cy-ay)*(px-cx)+(ax-cx)*(py-cy))/d; l3=1-l1-l2
        if l1>=0 and l2>=0 and l3>=0: n+=1
    return n
def one(mid):
    ev=json.load(open(f'/tmp/s360/ev/{mid}.json')); ff={f['event_uuid']:f for f in json.load(open(f'/tmp/s360/ff/{mid}.json'))}
    rows=[];shots=[]
    for e in ev:
        t=e['type']['name']
        if e['id'] not in ff: continue
        opp=[p['location'] for p in ff[e['id']]['freeze_frame'] if not p['teammate'] and not p.get('keeper')]
        allopp=[p['location'] for p in ff[e['id']]['freeze_frame'] if not p['teammate']]
        if t=='Pass' and 'outcome' not in e['pass'] and e['pass'].get('type',{}).get('name') not in ('Corner','Free Kick','Throw-in','Goal Kick','Kick Off'):
            sx,ex=e['location'][0],e['pass']['end_location'][0]
            byp=sum(1 for x,y in opp if sx < x < ex) if ex>sx else 0
            rows.append((mid,e['team']['name'],byp))
        elif t=='Shot' and e['shot']['type']['name']=='Open Play':
            sx,sy=e['location']
            shots.append((mid,e['team']['name'],tri_count(sx,sy,allopp),e['shot']['outcome']['name']=='Goal',e['shot'].get('statsbomb_xg',0),sx,sy))
    return rows,shots
if __name__=='__main__':
    ids=[int(x) for x in open('/tmp/s360/ids.txt').read().split()]
    R=[];S=[]
    with ProcessPoolExecutor(8) as ex:
        for r,s in ex.map(one,ids): R+=r; S+=s
    p=pd.DataFrame(R,columns=['match_id','team','bypassed']); s=pd.DataFrame(S,columns=['match_id','team','in_cone','goal','xg','x','y'])
    tm=p.groupby(['match_id','team']).bypassed.sum().reset_index()
    M=[]
    for f in glob.glob('/tmp/s360/m_*.json'):
        for m in json.load(open(f)):
            M.append((m['match_id'],m['home_team']['home_team_name'],m['away_team']['away_team_name'],m['home_score'],m['away_score'],m['competition']['competition_name'],m['season']['season_name']))
    M=pd.DataFrame(M,columns=['match_id','home','away','hs','as_','comp','season'])
    rows=[]
    for _,m in M.iterrows():
        bh=tm[(tm.match_id==m.match_id)&(tm.team==m.home)].bypassed.sum(); ba=tm[(tm.match_id==m.match_id)&(tm.team==m.away)].bypassed.sum()
        res='draw' if m.hs==m.as_ else ('more' if (m.hs>m.as_)==(bh>ba) else 'fewer')
        rows.append((m.match_id,m.comp,m.season,bh,ba,res))
    r=pd.DataFrame(rows,columns=['match_id','comp','season','bh','ba','res'])
    print(r.res.value_counts()); dec=r[r.res!='draw']; print('winner bypassed more:',round((dec.res=='more').mean(),3),'of',len(dec))
    print('all matches: team bypassing more won',round((r.res=='more').mean(),3),' drew',round((r.res=='draw').mean(),3),' lost',round((r.res=='fewer').mean(),3))
    print('avg opponents bypassed per pass',p.bypassed.mean().round(2),' per team-match',tm.bypassed.mean().round(1))
    g=s.groupby(s.in_cone.clip(upper=4)).agg(shots=('goal','size'),goals=('goal','sum'),conv=('goal','mean'),xg=('xg','mean'))
    print(g.round(3)); print('shots',len(s))
    r.to_csv('/tmp/s360/packing_matches.csv',index=False); g.to_csv('/tmp/s360/cone.csv'); s.to_csv('/tmp/s360/shots.csv',index=False); tm.to_csv('/tmp/s360/packing_team.csv',index=False)
