from db import get_connection


def replace_match_referees2(match_id: int, rows: list[dict]) -> None:
    delete_query = "DELETE FROM match_referees WHERE match_id = %s;"
    insert_query = """
    INSERT INTO match_referees (
        match_id,
        referee_id,
        referee_name,
        role,
        source,
        created_at,
        updated_at
    )
    VALUES (%s, %s, %s, %s, %s, NOW(), NOW());
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(delete_query, (match_id,))
            for row in rows:
                cur.execute(
                    insert_query,
                    (
                        row["match_id"],
                        row.get("referee_id"),
                        row["referee_name"],
                        row.get("role"),
                        row.get("source", "parser"),
                    ),
                )
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()

def replace_match_referees(match_id: int, rows: list[dict]) -> None:
    delete_query = "DELETE FROM match_referees WHERE match_id = %s;"
    insert_query = """
    INSERT INTO match_referees (
        match_id,
        referee_id,
        referee_name,
        role,
        source,
        created_at,
        updated_at
    )
    VALUES (%s, %s, %s, %s, %s, NOW(), NOW());
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(delete_query, (match_id,))

            for row in rows or []:
                referee_id = row.get("referee_id") or row.get("id")
                referee_name = (
                    row.get("referee_name")
                    or row.get("full_name")
                    or row.get("name")
                    or ""
                ).strip()
                role = (row.get("role") or "").strip()

                if not referee_name or not role:
                    continue

                cur.execute(
                    insert_query,
                    (
                        match_id,
                        referee_id,
                        referee_name,
                        role,
                        row.get("source", "admin"),
                    ),
                )

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

def get_match_referees(match_id: int) -> list[dict]:
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT
                    mr.referee_name,
                    mr.role
                FROM match_referees mr
                WHERE mr.match_id = %s
                ORDER BY
                    CASE mr.role
                        WHEN 'Главный судья' THEN 1
                        WHEN 'Ассистент судьи №1' THEN 2
                        WHEN 'Ассистент судьи №2' THEN 3
                        WHEN 'Резервный судья' THEN 4
                        WHEN 'Инспектор' THEN 5
                        WHEN 'Делегат' THEN 6
                        ELSE 99
                    END,
                    mr.referee_name
                """,
                (match_id,),
            )
            rows = cur.fetchall()

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


