import json
import os
import sys
from datetime import datetime

sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from src.lolpedia_api import (
    AuthCredentials,
    LeaguepediaClient,
    and_,
    desc,
    or_,
    select,
    tables,
)


def add_computed(data, name: str, callback):
    for d in data:
        d[name] = callback(d)
    return data


creds = AuthCredentials(user_file="bot")
client = LeaguepediaClient(creds)

P = tables.Player
SP = tables.ScoreboardPlayer
SG = tables.ScoreboardGame

statement = (
    select(
        P.Player,
        SP.Deaths,
        SP.Kills,
        SP.TeamVs,
        SP.Assists,
        SP.DamageToChampions,
        SG.Gamelength_Number,
        SG.DateTime_UTC,
    )
    .join(
        SP,
        onclause=P.Player == SP.Name,
    )
    .join(SG, onclause=SP.GameId == SG.GameId)
    .where(
        # This where return all calist games with (and)
        # - More than 10 kills
        # - A perfect KDA or a KDA more than 10
        # - DPM > 1000
        # - After 2025
        and_(
            P.Player == "caliste",
            SP.Kills > 10,
            SP.DamageToChampions / SG.Gamelength_Number > 1000,  # DPM more than 1k
            or_(
                SP.Deaths == 0,
                # and_(SP.Deaths != 0, (SP.Kills + SP.Assists) / SP.Deaths >= 10),
            ),  # KDA more than 10 or PERFECT
            SG.DateTime_UTC >= datetime(2025, 1, 1),
        )
    )
    .limit(50)
    .order_by(
        desc(SP.DamageToChampions / SG.Gamelength_Number),
    )
)

results = client.execute_query(statement)


print(
    json.dumps(
        add_computed(
            results,
            "dpm",
            lambda x: (float(x["DamageToChampions"]) / float(x["Gamelength Number"])),
        ),
        indent=4,
    )
)
print(f"\t - {len(results)} results ...")
