from repositories.match_repository import (
    get_match_by_external_id,
    mark_match_parsed,
    mark_match_parse_error,
    clear_match_squad_data,
)
from repositories.player_repository import (
    get_player_id_by_name_and_team,
    get_player_id_by_external_id,
)
from repositories.coach_repository import (
    get_coach_id_by_name_and_team,
    get_coach_id_by_external_id,
)
from repositories.referee_repository import get_referee_id_by_name, upsert_referee
from repositories.match_lineup_repository import replace_match_lineups, save_match_lineup_for_editor
from repositories.match_coach_repository import replace_match_coaches
from repositories.match_referee_repository import replace_match_referees


def sync_match_page(
    match_external_id: str,
    home_starting: list[dict],
    away_starting: list[dict],
    home_bench: list[dict],
    away_bench: list[dict],
    home_coaches: list[dict],
    away_coaches: list[dict],
    referees: list[dict],
) -> None:
    match_row = get_match_by_external_id(match_external_id)
    if not match_row:
        raise ValueError(f"Match not found by external_id: {match_external_id}")

    match_id, _, home_team_id, away_team_id = match_row
    clear_match_squad_data(match_id)

    lineup_rows = []
    for player in home_starting:
        player_id = None
        player_position = None

        if player.get("player_external_id"):
            player_id, player_position = get_player_id_by_external_id(player["player_external_id"])

        if player_id is None:
            player_id = get_player_id_by_name_and_team(
                player["player_name"], home_team_id
            )
        print(player_id, player_position)


        lineup_rows.append(
            {
                "match_id": match_id,
                "team_id": home_team_id,
                "player_id": player_id,
                "player_name": player["player_name"],
                "number": player.get("number"),
                "position": player.get("position"),
                "position_full": player_position,
                "is_captain": bool(player.get("is_captain")),
                "lineup_type": "starting",
                "source": "parser",
            }
        )

    for player in away_starting:
        player_id = None
        player_position = None

        if player.get("player_external_id"):
            player_id, player_position = get_player_id_by_external_id(player["player_external_id"])

        if player_id is None:
            player_id = get_player_id_by_name_and_team(
                player["player_name"], away_team_id
            )

        lineup_rows.append(
            {
                "match_id": match_id,
                "team_id": away_team_id,
                "player_id": player_id,
                "player_name": player["player_name"],
                "number": player.get("number"),
                "position": player.get("position"),
                "position_full": player_position,
                "is_captain": bool(player.get("is_captain")),
                "lineup_type": "starting",
                "source": "parser",
            }
        )

    for player in home_bench:
        player_id = None
        player_position = None

        if player.get("player_external_id"):
            player_id, player_position = get_player_id_by_external_id(player["player_external_id"])

        if player_id is None:
            player_id = get_player_id_by_name_and_team(
                player["player_name"], home_team_id
            )

        lineup_rows.append(
            {
                "match_id": match_id,
                "team_id": home_team_id,
                "player_id": player_id,
                "player_name": player["player_name"],
                "number": player.get("number"),
                "position": player.get("position"),
                "position_full": player_position,
                "is_captain": bool(player.get("is_captain")),
                "lineup_type": "bench",
                "source": "parser",
            }
        )

    for player in away_bench:
        player_id = None
        player_position = None

        if player.get("player_external_id"):
            player_id, player_position = get_player_id_by_external_id(player["player_external_id"])

        if player_id is None:
            player_id = get_player_id_by_name_and_team(
                player["player_name"], away_team_id
            )

        lineup_rows.append(
            {
                "match_id": match_id,
                "team_id": away_team_id,
                "player_id": player_id,
                "player_name": player["player_name"],
                "number": player.get("number"),
                "position": player.get("position"),
                "position_full": player_position,
                "is_captain": bool(player.get("is_captain")),
                "lineup_type": "bench",
                "source": "parser",
            }
        )

    coach_rows = []

    for coach in home_coaches:
        coach_id = None

        if coach.get("coach_external_id"):
            coach_id = get_coach_id_by_external_id(coach["coach_external_id"])

        if coach_id is None:
            coach_id = get_coach_id_by_name_and_team(coach["coach_name"], home_team_id)

        coach_rows.append(
            {
                "match_id": match_id,
                "team_id": home_team_id,
                "coach_id": coach_id,
                "coach_name": coach["coach_name"],
                "role": coach.get("role"),
                "source": "parser",
            }
        )

    for coach in away_coaches:
        coach_id = None

        if coach.get("coach_external_id"):
            coach_id = get_coach_id_by_external_id(coach["coach_external_id"])

        if coach_id is None:
            coach_id = get_coach_id_by_name_and_team(coach["coach_name"], away_team_id)

        coach_rows.append(
            {
                "match_id": match_id,
                "team_id": away_team_id,
                "coach_id": coach_id,
                "coach_name": coach["coach_name"],
                "role": coach.get("role"),
                "source": "parser",
            }
        )

    referee_rows = []

    for referee in referees:
        referee_name = referee["referee_name"].strip()
        referee_id = get_referee_id_by_name(referee_name)

        if referee_id is None:
            referee_id = upsert_referee(full_name=referee_name)

        referee_rows.append(
            {
                "match_id": match_id,
                "referee_id": referee_id,
                "referee_name": referee_name,
                "role": referee.get("role"),
                "source": "parser",
            }
        )

    try:
        replace_match_lineups(match_id, lineup_rows)
        for row in coach_rows:
            row["side"] = "home" if row["team_id"] == home_team_id else "away"
        replace_match_coaches(match_id, coach_rows)
        
        
        replace_match_referees(match_id, referee_rows)
        mark_match_parsed(match_external_id)
    except Exception as e:
        mark_match_parse_error(match_external_id, str(e))
        raise
