import logging
from typing import Any

from boardgames.models import BoardGame, BoardGameVariant

logger = logging.getLogger(__name__)


def board_names_to_variants(
    board_game: BoardGame, board_names: list[str]
) -> list[int]:
    """Given a board game and a list of board/scenario names, find or create
    BoardGameVariant records and return their IDs.

    Splits each name on the full-width slash ``／`` so that a single field
    containing ``Map A／Map B`` produces two separate variants.
    """
    variant_ids: list[int] = []
    for raw_name in board_names:
        for part in raw_name.split("／"):
            name = part.strip()
            if not name:
                continue
            variant, was_created = BoardGameVariant.objects.get_or_create(
                board_game=board_game,
                name=name,
            )
            logger.debug(
                "Resolved board variant",
                extra={
                    "board_game_id": board_game.id,
                    "variant_name": name,
                    "variant_id": variant.id,
                    "was_created": was_created,
                },
            )
            variant_ids.append(variant.id)
    return variant_ids


def fetch_and_link_expansions(
    board_game: BoardGame, expansions_data: list[dict[str, Any]]
) -> None:
    """Given a board game and a list of expansion dicts (with 'id' and 'name'),
    find or create each expansion BoardGame and link it via expansion_for_boardgame.
    """
    if board_game.skip_expansions:
        logger.info(
            "Skipping expansion fetch for board game with skip_expansions=True",
            extra={"board_game_id": board_game.id, "title": board_game.title},
        )
        return

    for exp_data in expansions_data:
        exp_id = exp_data.get("id")
        if not exp_id:
            continue
        expansion = BoardGame.find_or_create(str(exp_id))
        if expansion and expansion.id != board_game.id:
            expansion.expansion_for_boardgame = board_game
            expansion.save(update_fields=["expansion_for_boardgame"])
            logger.info(
                "Linked expansion to board game",
                extra={
                    "board_game_id": board_game.id,
                    "expansion_id": expansion.id,
                    "expansion_name": expansion.title,
                },
            )
