import secrets

from db import get_connection


def create_match_session(
    match_id: int,
    operator_name: str | None = None,
    vmix_project_path: str | None = None,
):
    session_token = secrets.token_urlsafe(24)

    query = """
    INSERT INTO match_sessions (
        match_id,
        operator_name,
        session_token,
        vmix_project_path,
        is_active,
        created_at,
        updated_at
    )
    VALUES (%s, %s, %s, %s, TRUE, NOW(), NOW())
    RETURNING id, match_id, operator_name, session_token, vmix_project_path, is_active, created_at, updated_at;
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                query, (match_id, operator_name, session_token, vmix_project_path)
            )
            row = cur.fetchone()
        conn.commit()
        return row
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def get_match_session_by_token(session_token: str):
    query = """
    SELECT
        ms.id,
        ms.match_id,
        ms.operator_name,
        ms.session_token,
        ms.vmix_project_path,
        ms.is_active,
        ms.created_at,
        ms.updated_at,

        m.external_id AS match_external_id,
        m.match_date,
        m.tour,
        m.season,
        m.place,

        ht.id AS home_team_id,
        ht.name AS home_team_name,
        ht.logo_url AS home_team_logo,
        ht.logo_path AS home_team_logo_path,

        at.id AS away_team_id,
        at.name AS away_team_name,
        at.logo_url AS away_team_logo,
        at.logo_path AS away_team_logo_path

    FROM match_sessions ms
    JOIN matches m ON m.id = ms.match_id
    JOIN teams ht ON ht.id = m.home_team_id
    JOIN teams at ON at.id = m.away_team_id
    WHERE ms.session_token = %s
    LIMIT 1;
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query, (session_token,))
            return cur.fetchone()
    finally:
        conn.close()
        

def deactivate_match_session(session_token: str) -> None:
    query = """
    UPDATE match_sessions
    SET is_active = FALSE,
        updated_at = NOW()
    WHERE session_token = %s;
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query, (session_token,))
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def update_match_session_vmix_path(session_token: str, vmix_project_path: str) -> None:
    query = """
    UPDATE match_sessions
    SET vmix_project_path = %s,
        updated_at = NOW()
    WHERE session_token = %s;
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query, (vmix_project_path, session_token))
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def get_match_by_id(match_id: int):
    query = """
    SELECT
        m.id,
        m.external_id,
        m.match_date,
        m.tour,
        m.season,
        ht.name AS home_team_name,
        at.name AS away_team_name
    FROM matches m
    JOIN teams ht ON ht.id = m.home_team_id
    JOIN teams at ON at.id = m.away_team_id
    WHERE m.id = %s
    LIMIT 1;
    """

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


def list_matches_for_admin(today_only: bool = False, tour: str | None = None):
    query = """
    SELECT
        m.id,
        m.external_id,
        m.match_date,
        m.status,
        m.tour,
        m.season,
        ht.name AS home_team_name,
        at.name AS away_team_name
    FROM matches m
    JOIN teams ht ON ht.id = m.home_team_id
    JOIN teams at ON at.id = m.away_team_id
    WHERE 1=1
    """
    params = []

    if today_only:
        query += " AND DATE(m.match_date) = CURRENT_DATE "

    if tour:
        query += " AND m.tour = %s "
        params.append(tour)

    query += " ORDER BY m.match_date ASC NULLS LAST, m.id ASC; "

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


def list_available_tours():
    query = """
    SELECT DISTINCT tour
    FROM matches
    WHERE tour IS NOT NULL AND tour <> '';
    """

    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query)
            tours = [row[0] for row in cur.fetchall()]

        def extract_tour_number(value: str):
            value = str(value).strip()
            digits = "".join(ch for ch in value if ch.isdigit())
            return int(digits) if digits else 999999

        tours.sort(key=lambda x: (extract_tour_number(x), str(x)))
        return tours
    finally:
        conn.close()

def list_matches_for_admin(
    today_only: bool = False,
    tour: str | None = None,
    hide_finished: bool = True,
):
    query = """
    SELECT
        m.id,
        m.external_id,
        m.match_date,
        m.status,
        m.tour,
        m.season,
        ht.name AS home_team_name,
        at.name AS away_team_name
    FROM matches m
    JOIN teams ht ON ht.id = m.home_team_id
    JOIN teams at ON at.id = m.away_team_id
    WHERE 1=1
    """
    params = []

    if today_only:
        query += " AND DATE(m.match_date) = CURRENT_DATE "

    if tour:
        query += " AND m.tour = %s "
        params.append(tour)

    if hide_finished:
        query += " AND COALESCE(m.status, 'scheduled') <> 'finished' "

    query += " ORDER BY m.match_date ASC NULLS LAST, m.id ASC; "

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