"""Blacklist and word filter checks."""
from __future__ import annotations

from typing import Optional

from cachetools import TTLCache as _TTLCache

from bot import db

_BLACKLIST_CACHE: _TTLCache = _TTLCache(maxsize=500, ttl=10)
_FILTERS_CACHE: _TTLCache = _TTLCache(maxsize=500, ttl=10)


async def check_blacklist(message, chat_id: int) -> bool:
    """Return True if a message contains a blacklisted word."""
    text = (message.text or message.caption or "").lower()
    if not text:
        return False
    if chat_id not in _BLACKLIST_CACHE:
        _BLACKLIST_CACHE[chat_id] = await db.get_blacklist_words(chat_id)
    words = _BLACKLIST_CACHE[chat_id]
    if not words:
        return False
    msg_words = set(text.split())
    for w in words:
        if len(w) < 2:
            continue
        if w in text:
            return True
    return False


async def check_word_filter(message, chat_id: int) -> Optional[tuple[str, str]]:
    """Check a message against saved word filters. Returns (keyword, response) if matched."""
    text = message.text or ""
    if not text:
        return None
    text_lower = text.lower()
    if chat_id not in _FILTERS_CACHE:
        _FILTERS_CACHE[chat_id] = await db.get_all_filters(chat_id)
    filters_ = _FILTERS_CACHE[chat_id]
    for f in filters_:
        kw = f["keyword"]
        if len(kw) < 2:
            continue
        if kw in text_lower:
            return (kw, f["response"] or "")
    return None
