from collections.abc import Iterable, Iterator
from typing import TypedDict

from folkugat_web.dal.sql import Connection, get_connection
from folkugat_web.dal.sql.sessions import conversion as sessions_conversion
from folkugat_web.model import playlists as model
from folkugat_web.model.sessions import Session
from folkugat_web.utils import groupby

from . import conversion


class QueryData(TypedDict, total=False):
    id: int
    set_id: int
    session_id: int


def _filter_clause(
    entry_id: int | None = None,
    set_id: int | None = None,
    session_id: int | None = None,
) -> tuple[str, QueryData]:
    filter_clauses: list[str] = []
    query_data: QueryData = {}

    if entry_id is not None:
        filter_clauses.append("id = :id")
        query_data["id"] = entry_id
    if set_id is not None:
        filter_clauses.append("set_id = :set_id")
        query_data["set_id"] = set_id
    if session_id is not None:
        filter_clauses.append("session_id = :session_id")
        query_data["session_id"] = session_id

    return " AND ".join(filter_clauses), query_data


def get_playlist_entries(
    entry_id: int | None = None,
    set_id: int | None = None,
    session_id: int | None = None,
    con: Connection | None = None,
) -> Iterator[model.PlaylistEntry]:
    filter_clause, data = _filter_clause(entry_id=entry_id, set_id=set_id, session_id=session_id)
    query = f"""
      SELECT
        id, session_id, set_id, tema_id
      FROM playlists
      WHERE {filter_clause}
    """
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        return map(conversion.row_to_playlist_entry, cur.fetchall())


GetTuneSessionsRow = tuple[int, int, str, str, str, str | None, str | None, bool]


def get_tune_sessions(tema_ids: list[int], con: Connection | None = None) -> dict[int, list[Session]]:
    placeholders = ", ".join(["?" for _ in tema_ids])
    query = f"""
      SELECT p.tema_id, s.id, s.date, s.start_time, s.end_time, s.venue_name, s.venue_url, s.is_live
      FROM playlists p JOIN sessions s ON p.session_id = s.id
      WHERE p.tema_id IN ({placeholders})
    """
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, tema_ids)
        result_rows: Iterable[GetTuneSessionsRow] = cur.fetchall()
        return dict(groupby(
            result_rows,
            key_fn=lambda row: row[0],
            group_fn=lambda rows: list(sessions_conversion.row_to_session(row[1:]) for row in rows)
        ))
