from collections.abc import Iterable

from folkugat_web.dal.sql.sessions import playlists as session_playlists
from folkugat_web.dal.sql.temes import query as temes_q
from folkugat_web.model import sessions as sessions_model
from folkugat_web.model import temes as model


def get_tema_by_id(tema_id: int) -> model.Tema | None:
    return temes_q.get_tema_by_id(tema_id=tema_id)


def get_temes_by_ids(tema_ids: list[int]) -> list[model.Tema]:
    return temes_q.get_temes_by_ids(tema_ids=tema_ids)


def tema_compute_stats(
    tema: model.Tema,
    tune_sessions_dict: dict[int, list[sessions_model.Session]] | None = None,
) -> model.Tema:
    if tema.id:
        if tune_sessions_dict is None:
            tune_sessions_dict = session_playlists.get_tune_sessions(tema_ids=[tema.id])
        if tema.id and (tune_sessions := tune_sessions_dict.get(tema.id)):
            unique_tune_sessions = set(tune_sessions)
            tema.stats = model.Stats(
                times_played=len(unique_tune_sessions),
                sessions_played=list(reversed(sorted(unique_tune_sessions, key=lambda s: s.date))),
            )
    return tema


def temes_compute_stats(temes: Iterable[model.Tema]) -> list[model.Tema]:
    temes = list(temes)
    tema_ids = [tema.id for tema in temes if tema.id is not None]
    tune_sessions_dict = session_playlists.get_tune_sessions(tema_ids=tema_ids)
    return [tema_compute_stats(tema=tema, tune_sessions_dict=tune_sessions_dict) for tema in temes]


def tema_compute_played_with(
    tema: model.Tema,
) -> model.Tema:
    if tema.id:
        tema.played_with = session_playlists.get_commonly_played_tunes(tema_id=tema.id)
    return tema
