from repositories.player_repository import upsert_player
from repositories.coach_repository import upsert_coach


def to_int(value, default=0) -> int:
    if value is None:
        return default
    value = str(value).strip()
    return int(value) if value.isdigit() else default


def sync_team_roster(team_external_id: str, team_data: dict) -> None:
    players = team_data.get("players") or []
    coaches = team_data.get("coaches") or []

    for player in players:
        upsert_player(
            external_id=player.get("player_id", ""),
            team_external_id=team_external_id,
            player=player.get("player", ""),
            lastname=player.get("lastname", ""),
            name=player.get("name", ""),
            number=player.get("number", ""),
            pos=player.get("pos", ""),
            amplua=player.get("amplua", ""),
            born=player.get("born", ""),
            games=to_int(player.get("games")),
            goals=to_int(player.get("goals")),
            penaltys=to_int(player.get("penaltys")),
            assists=to_int(player.get("assists")),
            yellows=to_int(player.get("yellows")),
            reds=to_int(player.get("reds")),
            is_active=True,
        )

    for coach in coaches:
        upsert_coach(
            external_id=coach.get("coach_id", ""),
            team_external_id=team_external_id,
            player=coach.get("player", ""),
            lastname=coach.get("lastname", ""),
            name=coach.get("name", ""),
            born=coach.get("born", ""),
            amplua=coach.get("amplua", ""),
            is_active=True,
        )