"""Global error handler: log exception and notify user."""

import logging

from telegram import Update
from telegram.ext import ContextTypes

import duty_teller.config as config
from duty_teller.i18n import get_lang, t

logger = logging.getLogger(__name__)


async def error_handler(
    update: Update | None, context: ContextTypes.DEFAULT_TYPE
) -> None:
    """Global error handler: log exception and reply with generic message if possible.

    Args:
        update: Update that caused the error (may be None).
        context: Callback context.
    """
    logger.exception("Exception while handling an update")
    if isinstance(update, Update) and update.effective_message:
        try:
            user = getattr(update, "effective_user", None)
            lang = get_lang(user) if user else config.DEFAULT_LANGUAGE
            await update.effective_message.reply_text(t(lang, "errors.generic"))
        except Exception:
            logger.warning("Could not send error reply to user", exc_info=True)
