"""Moderation pipeline orchestration."""

from __future__ import annotations

from telegram.error import BadRequest, Forbidden

from bot.core.metrics import incr
from bot.helpers import extract_links
from bot.services.locks import check_media_locks, check_text_locks


async def apply_moderation(message, context, runtime) -> bool:
    """Returns True if message processing should stop."""

    if runtime.privileged or not runtime.bot_is_admin:
        return False

    if runtime.settings.get_bool("muteall"):
        incr("moderation.muteall")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    from bot.handlers.listener.flood import check_flood

    if await check_flood(
        context.bot,
        context,
        message,
        runtime.chat_id,
        runtime.user_id,
        runtime.settings,
    ):
        return True

    violated = await check_media_locks(message, runtime.locks)

    if violated:
        incr(f"moderation.lock.{violated}")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    violated = await check_text_locks(message, runtime.locks)

    if violated:
        incr(f"moderation.lock.{violated}")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    from bot.handlers.listener.antispam import check_blacklist

    if await check_blacklist(message, runtime.chat_id):
        incr("moderation.blacklist")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    is_forward = bool(message.forward_origin) if hasattr(message, "forward_origin") else False

    if is_forward and "forward" in runtime.locks:
        incr("moderation.forward")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    msg_text = message.text or message.caption or ""

    if "webpage" in runtime.locks and msg_text and extract_links(msg_text):
        incr("moderation.webpage")

        try:
            await message.delete()
        except (BadRequest, Forbidden):
            pass

        return True

    return False
