import os
import sys
from datetime import datetime

from pydantic import BaseModel

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

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

P = tables.Player
PR = tables.PlayerRedirect
SP = tables.ScoreboardPlayer
SG = tables.ScoreboardGame
ST = tables.ScoreboardTeam


class Result(BaseModel):
    Role: str
    GameId: str
    max_gold: int
    min_gold: int
    Team1: str
    Team2: str

    @property
    def gold_difference(self):
        return self.max_gold - self.min_gold


def get_gold_diff(
    client: LeaguepediaClient, role: str | None = None, limit: int = 10
) -> list[Result]:
    statement = (
        select(
            SP.Role,
            SP.GameId,
            SG.Tournament,
            SG.Team1,
            SG.Team2,
            func.max(SP.Gold).label("max_gold"),
            func.min(SP.Gold).label("min_gold"),
        )
        .select_from(SP)
        .join(SG, SG.GameId == SP.GameId)
        .where(
            # In case we put true SQLAlchemy just ignore the where
            and_(
                SP.Role == role if role is not None else True,
                or_(
                    SG.Tournament.like(r"LEC%"),
                    SG.Tournament.like(r"EU LCS%"),
                ),
                SP.DateTime_UTC >= datetime(2017, 1, 1),
            )
        )
        .group_by(SP.GameId, SP.Role)
        .order_by(desc(text("(max_gold - min_gold)")))
        .limit(limit)
    )

    return client.execute_query(statement, model=Result)


def show_result(data: list[Result], role: str) -> None:
    print(f"{'=' * 25}{role.upper().center(9)}{'=' * 25}")
    for row in data:
        print(
            f"GoldDiff={row.gold_difference} - GameId={row.GameId} ({row.Team1} vs {row.Team2})"
        )
    print()


def main():
    creds = AuthCredentials(user_file="bot")
    client = LeaguepediaClient(creds)

    gold_diffs = get_gold_diff(client, None, limit=5)
    show_result(gold_diffs, "ANY ROLE")

    for role in ["Top", "Jungle", "Mid", "Bot", "Support"]:
        gold_diffs = get_gold_diff(client, role, limit=5)
        show_result(gold_diffs, role)


if __name__ == "__main__":
    main()
