from db import get_connection


def get_match_coaches_grouped(
    match_id: int,
    home_team_id: int | None = None,
    away_team_id: int | None = None,
) -> dict:
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT
                    mc.side,
                    mc.coach_id,
                    COALESCE(c.player, c.name, '') AS coach_name,
                    COALESCE(mc.role, c.amplua, '') AS role
                FROM match_coaches mc
                JOIN coaches c
                    ON c.id = mc.coach_id
                WHERE mc.match_id = %s
                ORDER BY mc.side, mc.sort_order, mc.id
                """,
                (match_id,),
            )
            rows = cur.fetchall()

        result = {
            "home": [],
            "away": [],
        }

        for row in rows:
            item = {
                "coach_id": row[1],
                "coach_name": row[2] or "",
                "role": row[3] or "",
            }

            if row[0] == "home":
                result["home"].append(item)
            elif row[0] == "away":
                result["away"].append(item)

        return result
    finally:
        conn.close()


def replace_match_coaches(match_id: int, *args) -> None:
    """
    Поддерживает оба варианта вызова:
    1) replace_match_coaches(match_id, coach_rows)
    2) replace_match_coaches(match_id, home_team_id, away_team_id, home_coaches, away_coaches)
    """
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                "DELETE FROM match_coaches WHERE match_id = %s",
                (match_id,),
            )

            if len(args) == 1:
                coach_rows = args[0] or []
                sort_counters = {
                    "home": 1,
                    "away": 1,
                }

                for coach in coach_rows:
                    side = coach.get("side")

                    if side not in ("home", "away"):
                        team_side = coach.get("team_id")
                        if team_side in ("home", "away"):
                            side = team_side
                        else:
                            continue

                    coach_id = coach.get("coach_id")
                    if not coach_id:
                        continue

                    cur.execute(
                        """
                        INSERT INTO match_coaches (
                            match_id,
                            side,
                            sort_order,
                            coach_id,
                            role
                        )
                        VALUES (%s, %s, %s, %s, %s)
                        """,
                        (
                            match_id,
                            side,
                            sort_counters[side],
                            coach_id,
                            coach.get("role") or coach.get("amplua") or None,
                        ),
                    )

                    sort_counters[side] += 1

            elif len(args) == 4:
                _home_team_id, _away_team_id, home_coaches, away_coaches = args

                def insert_side(side: str, coaches: list[dict]) -> None:
                    sort_order = 1

                    for coach in coaches or []:
                        coach_id = coach.get("coach_id")
                        if not coach_id:
                            continue

                        cur.execute(
                            """
                            INSERT INTO match_coaches (
                                match_id,
                                side,
                                sort_order,
                                coach_id,
                                amplua
                            )
                            VALUES (%s, %s, %s, %s, %s)
                            """,
                            (
                                match_id,
                                side,
                                sort_order,
                                coach_id,
                                coach.get("role") or coach.get("amplua") or None,
                            ),
                        )
                        sort_order += 1

                insert_side("home", home_coaches)
                insert_side("away", away_coaches)

            else:
                raise TypeError(
                    "replace_match_coaches() expected either "
                    "(match_id, coach_rows) or "
                    "(match_id, home_team_id, away_team_id, home_coaches, away_coaches)"
                )

        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()