from typing import Any, Union
from boardgamegeek import BGGClient

from django.conf import settings


def lookup_boardgame_from_bgg(
    lookup_id: str | None = None, title: str | None = None
) -> dict[str, Any]:
    game_dict: dict[str, Any] = {}

    bgg = BGGClient(access_token=settings.BGG_ACCESS_TOKEN)

    if lookup_id:
        game = bgg.game(game_id=lookup_id)
    else:
        game = bgg.game(title)

    if game:
        game_dict["title"] = game.name
        game_dict["description"] = game.description
        game_dict["published_year"] = game.yearpublished
        game_dict["cover_url"] = game.image
        game_dict["min_players"] = game.minplayers
        game_dict["max_players"] = game.maxplayers
        game_dict["recommended_age"] = game.minage
        game_dict["rating"] = game.rating_average
        game_dict["bggeek_id"] = game.id
        game_dict["bgg_rank"] = game.bgg_rank
        game_dict["base_run_time_seconds"] = (
            int(game.playingtime) * 60 if game.playingtime else None
        )
        game_dict["mechanics"] = game.mechanics
        game_dict["categories"] = game.categories
        game_dict["families"] = game.families
        game_dict["designers"] = game.designers
        game_dict["publishers"] = game.publishers
        if game.publishers:
            game_dict["publisher"] = game.publishers[0]
        game_dict["expansions"] = [
            {"id": exp.id, "name": exp.name} for exp in game.expansions
        ]

    return game_dict
