# retoor <retoor@molodetz.nl>

from .core import TTLCache, bump_cache_version, db, sync_local_cache


_relations_cache = TTLCache(ttl=300, max_size=2000)


def get_user_relations(viewer_uid: str | None) -> dict:
    if not viewer_uid:
        return {"block": frozenset(), "mute": frozenset()}
    sync_local_cache("relations", _relations_cache)
    cached = _relations_cache.get(viewer_uid)
    if cached is not None:
        return cached
    block: set = set()
    mute: set = set()
    if "user_relations" in db.tables:
        for row in db["user_relations"].find(user_uid=viewer_uid, deleted_at=None):
            target = row["target_uid"]
            if row["kind"] == "block":
                block.add(target)
            elif row["kind"] == "mute":
                mute.add(target)
    result = {"block": frozenset(block), "mute": frozenset(mute)}
    _relations_cache.set(viewer_uid, result)
    return result


def get_blocked_uids(viewer_uid: str | None) -> frozenset:
    return get_user_relations(viewer_uid)["block"]


def get_muted_uids(viewer_uid: str | None) -> frozenset:
    return get_user_relations(viewer_uid)["mute"]


def get_silenced_uids(viewer_uid: str | None) -> frozenset:
    relations = get_user_relations(viewer_uid)
    return relations["block"] | relations["mute"]


def invalidate_user_relations(viewer_uid: str) -> None:
    _relations_cache.pop(viewer_uid)
    bump_cache_version("relations")
