"""Download StatsBomb Open Data event files for the matches used in the article
and extract every carry, take-on and shot by Mbappe, Messi and Cristiano Ronaldo,
plus per-match counts and minutes played.

Usage:  python statsbomb_extract.py [data_dir]
Output: <data_dir>/extracted.pkl

Data: StatsBomb Open Data, https://github.com/statsbomb/open-data
"""
import json
import math
import os
import pickle
import sys
import urllib.request
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor

BASE = "https://raw.githubusercontent.com/statsbomb/open-data/master/data"
DATA = sys.argv[1] if len(sys.argv) > 1 else "statsbomb_data"

# (competition_id, season_id) in StatsBomb Open Data
COMPS = {
    "wc18": (43, 3), "wc22": (43, 106), "euro20": (55, 43), "euro24": (55, 282),
    "l1_2122": (7, 108), "l1_2223": (7, 235),
    "ll_0910": (11, 21), "ll_1011": (11, 22), "ll_1112": (11, 23), "ll_1213": (11, 24),
    "ll_1314": (11, 25), "ll_1415": (11, 26), "ll_1516": (11, 27),
}
# which teams' matches to keep per competition (None = every match released)
TEAMS = {
    "wc18": {"France", "Argentina", "Portugal"}, "wc22": {"France", "Argentina", "Portugal"},
    "euro20": {"France", "Portugal"}, "euro24": {"France", "Portugal"},
    "l1_2122": None, "l1_2223": None, "ll_1011": None, "ll_1112": None,
    "ll_0910": {"Real Madrid"}, "ll_1213": {"Real Madrid"}, "ll_1314": {"Real Madrid"},
    "ll_1415": {"Real Madrid"}, "ll_1516": {"Real Madrid"},
}
KEYS = {"Mbapp": "Mbappe", "Messi": "Messi", "Cristiano Ronaldo": "Ronaldo"}
SX, SY = 105 / 120, 68 / 80  # StatsBomb pitch units to metres
ACTIONS = {"Pass", "Shot", "Dribble", "Dispossessed", "Miscontrol", "Foul Won", "Carry"}


def fetch(url, path):
    if not (os.path.exists(path) and os.path.getsize(path) > 0):
        urllib.request.urlretrieve(url, path)


def who(name):
    if not name:
        return None
    for k, v in KEYS.items():
        if k in name:
            return v
    return None


def dist(a, b):
    return math.hypot((a[0] - b[0]) * SX, (a[1] - b[1]) * SY)


def ts(e):
    h, m, s = e["timestamp"].split(":")
    return int(h) * 3600 + int(m) * 60 + float(s)


def in_box(loc):
    return loc[0] >= 102 and 18 <= loc[1] <= 62


def select_matches():
    os.makedirs(f"{DATA}/matches", exist_ok=True)
    os.makedirs(f"{DATA}/events", exist_ok=True)
    sel = {}
    for comp, (c, s) in COMPS.items():
        path = f"{DATA}/matches/{comp}.json"
        fetch(f"{BASE}/matches/{c}/{s}.json", path)
        for x in json.load(open(path)):
            h, a = x["home_team"]["home_team_name"], x["away_team"]["away_team_name"]
            if TEAMS[comp] is None or h in TEAMS[comp] or a in TEAMS[comp]:
                sel[str(x["match_id"])] = dict(comp=comp, home=h, away=a, date=x["match_date"])
    with ThreadPoolExecutor(12) as ex:
        list(ex.map(lambda m: fetch(f"{BASE}/events/{m}.json", f"{DATA}/events/{m}.json"), sel))
    return sel


def minutes_played(ev):
    """Minutes on the pitch per tracked player, from line-ups, substitutions and red cards."""
    pend = defaultdict(float)
    for e in ev:
        if e["period"] <= 4:
            pend[e["period"]] = max(pend[e["period"]], ts(e))
    mins, start = defaultdict(float), {}

    def close(p, per, t):
        if p in start:
            sp, st = start.pop(p)
            tot = 0
            for q in range(sp, per + 1):
                a = st if q == sp else 0
                b = t if q == per else pend[q]
                tot += max(0, b - a)
            mins[p] += tot / 60

    for e in ev:
        if e["type"]["name"] == "Starting XI":
            for l in e["tactics"]["lineup"]:
                w = who(l["player"]["name"])
                if w:
                    start[w] = (1, 0.0)
        if e["period"] > 4:
            continue
        if e["type"]["name"] == "Substitution":
            w = who(e["player"]["name"])
            if w:
                close(w, e["period"], ts(e))
            w2 = who(e["substitution"]["replacement"]["name"])
            if w2:
                start[w2] = (e["period"], ts(e))
        card = None
        for k in ("foul_committed", "bad_behaviour"):
            if k in e and "card" in e[k]:
                card = e[k]["card"]["name"]
        if card in ("Red Card", "Second Yellow"):
            w = who(e.get("player", {}).get("name"))
            if w:
                close(w, e["period"], ts(e))
    last = max(pend) if pend else 2
    for p in list(start):
        close(p, last, pend[last])
    return mins


def extract(sel):
    carries, takeons, shots, agg, links = [], [], [], [], []
    for mid, meta in sel.items():
        ev = json.load(open(f"{DATA}/events/{mid}.json"))
        ev.sort(key=lambda e: e["index"])
        mins = minutes_played(ev)
        if not mins:
            continue
        byid = {e["id"]: e for e in ev}
        counts = defaultdict(lambda: defaultdict(float))
        pidx = defaultdict(list)
        for i, e in enumerate(ev):
            w = who(e.get("player", {}).get("name"))
            if w and e["period"] <= 4:
                pidx[w].append(i)
        for w, idxs in pidx.items():
            team = None
            for n, i in enumerate(idxs):
                e = ev[i]
                ty = e["type"]["name"]
                team = e["team"]["name"]
                loc = e.get("location")
                c = counts[w]
                if ty == "Pressure":
                    c["pressures"] += 1
                if ty == "Ball Receipt*" and "ball_receipt" not in e:
                    c["receipts"] += 1
                    if loc and in_box(loc):
                        c["rec_box"] += 1
                if ty == "Pass":
                    p = e["pass"]
                    c["passes"] += 1
                    done = "outcome" not in p
                    if p.get("shot_assist") or p.get("goal_assist"):
                        c["key_passes"] += 1
                    if p.get("goal_assist"):
                        c["assists"] += 1
                    if p.get("through_ball") or p.get("technique", {}).get("name") == "Through Ball":
                        c["through_balls"] += 1
                    el = p.get("end_location")
                    if (done and el and loc and in_box(el) and not in_box(loc)
                            and p.get("type", {}).get("name") not in ("Corner", "Free Kick", "Throw-in")):
                        c["passes_into_box"] += 1
                    r = who(p.get("recipient", {}).get("name"))
                    if r and r != w:
                        links.append(dict(mid=mid, comp=meta["comp"], src=w, dst=r,
                                          through=bool(p.get("through_ball") or p.get("technique", {}).get("name") == "Through Ball"),
                                          shot_assist=bool(p.get("shot_assist") or p.get("goal_assist")),
                                          goal_assist=bool(p.get("goal_assist"))))
                if ty == "Carry":
                    el = e["carry"]["end_location"]
                    d, du = dist(loc, el), e.get("duration") or 0
                    nxt, det = None, None
                    for j in idxs[n + 1:n + 6]:
                        f = ev[j]
                        if f["possession"] != e["possession"]:
                            break
                        if f["type"]["name"] in ACTIONS and f["period"] == e["period"] and ts(f) - (ts(e) + du) <= 2.5:
                            nxt = f["type"]["name"]
                            if nxt == "Dribble":
                                det = f["dribble"]["outcome"]["name"]
                            break
                    carries.append(dict(mid=mid, comp=meta["comp"], player=w, d=d, dur=du,
                                        x0=loc[0], y0=loc[1], x1=el[0], y1=el[1], nxt=nxt, det=det))
                    c["carries"] += 1
                    c["carry_m"] += d
                if ty == "Dribble":
                    takeons.append(dict(mid=mid, comp=meta["comp"], player=w,
                                        ok=e["dribble"]["outcome"]["name"] == "Complete"))
                if ty == "Shot":
                    s = e["shot"]
                    shots.append(dict(mid=mid, comp=meta["comp"], player=w, xg=s.get("statsbomb_xg", 0),
                                      goal=s["outcome"]["name"] == "Goal", stype=s["type"]["name"],
                                      body=s["body_part"]["name"], first_time=bool(s.get("first_time")),
                                      one_on_one=bool(s.get("one_on_one")), up=bool(e.get("under_pressure")),
                                      x=loc[0], y=loc[1]))
            agg.append(dict(mid=mid, comp=meta["comp"], player=w, team=team, minutes=mins.get(w, 0), **counts[w]))
    return dict(carries=carries, takeons=takeons, shots=shots, agg=agg, links=links)


if __name__ == "__main__":
    selected = select_matches()
    out = extract(selected)
    pickle.dump(out, open(f"{DATA}/extracted.pkl", "wb"))
    print(len(selected), "matches;", {k: len(v) for k, v in out.items()})
