from typing import Optional

from folkugat_web.dal.sql import Connection, get_connection
from folkugat_web.model import temes as model

from ._conversion import cell_to_ngrams, row_to_tema

TEMA_ID_TO_NGRAMS_CACHE = None


def get_tema_by_id(tema_id: int, con: Optional[Connection] = None) -> Optional[model.Tema]:
    query = """
      SELECT
        id, title, properties, links, lyrics, alternatives, ngrams,
        creation_date, modification_date, hidden
      FROM temes
      WHERE id = :id
    """
    data = dict(id=tema_id)
    with get_connection(con) as con:
        cur = con.cursor()
        cur.execute(query, data)
        row = cur.fetchone()
        return row_to_tema(row) if row else None


def evict_tema_id_to_ngrams_cache():
    global TEMA_ID_TO_NGRAMS_CACHE
    TEMA_ID_TO_NGRAMS_CACHE = None


def get_tema_id_to_ngrams(con: Optional[Connection] = None) -> dict[int, model.NGrams]:
    global TEMA_ID_TO_NGRAMS_CACHE
    if TEMA_ID_TO_NGRAMS_CACHE is None:
        TEMA_ID_TO_NGRAMS_CACHE = _get_tema_id_to_ngrams(con)
    return TEMA_ID_TO_NGRAMS_CACHE


def _get_tema_id_to_ngrams(con: Optional[Connection] = None) -> dict[int, model.NGrams]:
    query = """
      SELECT id, ngrams
      FROM temes
      WHERE hidden = 0
    """
    with get_connection(con) as con:
        cur = con.cursor()
        cur.execute(query)
        rows = cur.fetchall()
        return {id_: cell_to_ngrams(ng) for id_, ng in rows}
