from db import get_connection


def get_team_players_for_match_editor(
    team_id: int,
    match_id: int | None = None,
    home_team_id: int | None = None,
    away_team_id: int | None = None,
) -> list[dict]:
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT
                    p.id AS player_id,
                    COALESCE(
                        p.full_name,
                        TRIM(COALESCE(p.last_name, '') || ' ' || COALESCE(p.first_name, ''))
                    ) AS player_name,
                    COALESCE(p.last_name, '') AS last_name,
                    COALESCE(p.first_name, '') AS first_name,
                    COALESCE(p.number::text, '') AS number,
                    COALESCE(p.position, '') AS position,
                    FALSE AS is_captain
                FROM players p
                WHERE p.team_id = %s
                ORDER BY
                    CASE
                        WHEN LOWER(COALESCE(p.position, '')) IN ('вр', 'вр.', 'gk', 'goalkeeper', 'вратарь') THEN 0
                        ELSE 1
                    END,
                    CASE
                        WHEN COALESCE(p.number::text, '') ~ '^[0-9]+$' THEN p.number::integer
                        ELSE 999
                    END,
                    COALESCE(p.last_name, ''),
                    COALESCE(p.first_name, ''),
                    p.id
                """,
                (team_id,),
            )
            rows = cur.fetchall()

        return [
            {
                "player_id": row[0],
                "player_name": row[1] or "",
                "last_name": row[2] or "",
                "first_name": row[3] or "",
                "number": row[4] or "",
                "position": row[5] or "",
                "is_captain": bool(row[6]),
            }
            for row in rows
        ]
    finally:
        conn.close()