from repositories.match_coach_repository import get_match_coaches_grouped
from db import get_connection

def _normalize_coach(c: dict) -> dict:
    return {
        "coach_id": c.get("coach_id"),
        "coach_name": c.get("coach_name", "") or "",
        "role": c.get("role", "") or "",
    }


def get_team_coaches_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
                    c.id AS coach_id,
                    COALESCE(c.player, c.name, '') AS coach_name,
                    COALESCE(c.amplua, '') AS role
                FROM coaches c
                WHERE c.team_id = %s
                ORDER BY
                    CASE
                        WHEN LOWER(COALESCE(c.amplua, '')) LIKE '%%глав%%' THEN 0
                        ELSE 1
                    END,
                    COALESCE(c.player, c.name, ''),
                    c.id
                """,
                (team_id,),
            )
            rows = cur.fetchall()

        return [
            {
                "coach_id": row[0],
                "coach_name": row[1] or "",
                "role": row[2] or "",
            }
            for row in rows
        ]
    finally:
        conn.close()