from db import get_connection


def get_match_lineups_grouped(match_id: int, home_team_id: int, away_team_id: int):
    query = """
    SELECT
        ml.team_id,
        ml.player_id,
        ml.player_name,
        ml.number,
        p.position,
        ml.lineup_type,
        ml.is_captain,
        p.last_name,
        p.first_name, 
        p.position as pos
    FROM match_lineups ml
    LEFT JOIN players p ON p.id = ml.player_id
    WHERE ml.match_id = %s;
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query, (match_id,))
            rows = cur.fetchall()
    finally:
        conn.close()

    grouped = {
        "home_starting": [],
        "away_starting": [],
        "home_bench": [],
        "away_bench": [],
    }

    for row in rows:
        (
            team_id,
            player_id,
            player_name,
            number,
            position,
            lineup_type,
            is_captain,
            last_name,
            first_name,
            pos,
        ) = row

        item = {
            "player_id": player_id,
            "number": number or "",
            "last_name": last_name or "",
            "first_name": first_name or "",
            "player_name": player_name or "",
            "position": position or "",
            "is_captain": bool(is_captain),
            "pos": pos,
        }

        if team_id == home_team_id and lineup_type == "starting":
            grouped["home_starting"].append(item)
        elif team_id == away_team_id and lineup_type == "starting":
            grouped["away_starting"].append(item)
        elif team_id == home_team_id and lineup_type == "bench":
            grouped["home_bench"].append(item)
        elif team_id == away_team_id and lineup_type == "bench":
            grouped["away_bench"].append(item)

    def is_goalkeeper(position: str) -> int:
        pos = (position or "").strip().lower()
        goalkeeper_values = {"вр.", "вр", "вратарь", "goalkeeper", "gk"}
        return 0 if pos in goalkeeper_values else 1

    def player_number_value(number: str) -> int:
        number = str(number or "").strip()
        return int(number) if number.isdigit() else 999

    def sort_players(players: list[dict]) -> list[dict]:
        return sorted(
            players,
            key=lambda p: (
                is_goalkeeper(p.get("position", "")),
                player_number_value(p.get("number", "")),
                p.get("last_name", "") or p.get("player_name", ""),
                p.get("first_name", ""),
            ),
        )

    grouped["home_starting"] = sort_players(grouped["home_starting"])
    grouped["away_starting"] = sort_players(grouped["away_starting"])
    grouped["home_bench"] = sort_players(grouped["home_bench"])
    grouped["away_bench"] = sort_players(grouped["away_bench"])

    return grouped