
from plugins import Plugin, PluginMeta, PluginSetting, PluginSettingType, HookType
from typing import Optional, Dict, Any, List
import time
import re

TRANSLATIONS: dict[str, dict[str, str]] = {
    "en": {

        "setting_enabled": "Auto-Answer Enabled",
        "setting_enabled_desc": "Enable automatic handling of chat requests",
        "setting_mode": "Default Action",
        "setting_mode_desc": "What to do with requests that don't match any rule",
        "mode_manual": "Manual (Ask)",
        "mode_accept": "Auto Accept",
        "mode_decline": "Auto Decline",
        "setting_delay": "Action Delay (seconds)",
        "setting_delay_desc": "Wait this many seconds before auto-accepting/declining",
        "setting_whitelist": "Whitelist (aliases)",
        "setting_whitelist_desc": "Always accept requests from these aliases (one per line)",
        "setting_blacklist": "Blacklist (aliases)",
        "setting_blacklist_desc": "Always decline requests from these aliases (one per line)",
        "setting_custom_code": "Custom Python Code",
        "setting_custom_code_desc": "Advanced: Python code that returns 'accept', 'decline', or 'manual'",
        "setting_log_actions": "Log Actions",
        "setting_log_actions_desc": "Show notifications when auto-accepting/declining",
        "setting_min_age": "Minimum Request Age (seconds)",
        "setting_min_age_desc": "Only auto-process requests older than this (0 = immediate)",
        "setting_pattern_whitelist": "Whitelist Regex Pattern",
        "setting_pattern_whitelist_desc": "Regex pattern to match aliases to accept (empty = disabled)",
        "setting_pattern_blacklist": "Blacklist Regex Pattern",
        "setting_pattern_blacklist_desc": "Regex pattern to match aliases to decline (empty = disabled)",

        "cmd_autoaccept_desc": "Toggle auto-accept mode",
        "cmd_autoaccept_usage": "/autoaccept [on|off]",
        "cmd_autorules_desc": "Show current auto-answer rules",
        "cmd_autorules_usage": "/autorules",

        "auto_accepted": "✅ Auto-accepted request from {alias}",
        "auto_declined": "❌ Auto-declined request from {alias}",
        "auto_accept_on": "Auto-accept mode enabled",
        "auto_accept_off": "Auto-accept mode disabled (manual mode)",
        "rules_header": "📋 Auto-Answer Rules:",
        "rules_mode": "Default action: {mode}",
        "rules_delay": "Delay: {delay}s",
        "rules_whitelist": "Whitelist: {list}",
        "rules_blacklist": "Blacklist: {list}",
        "rules_pattern_wl": "Whitelist pattern: {pattern}",
        "rules_pattern_bl": "Blacklist pattern: {pattern}",
        "rules_custom": "Custom code: {status}",
        "code_error": "⚠️ Custom code error: {error}",
        "none": "(none)",
        "active": "active",
        "inactive": "inactive",
    },
    "tr": {

        "setting_enabled": "Otomatik Yanıt Aktif",
        "setting_enabled_desc": "Sohbet isteklerinin otomatik işlenmesini etkinleştir",
        "setting_mode": "Varsayılan İşlem",
        "setting_mode_desc": "Hiçbir kurala uymayan istekler için ne yapılacak",
        "mode_manual": "Manuel (Sor)",
        "mode_accept": "Otomatik Kabul",
        "mode_decline": "Otomatik Reddet",
        "setting_delay": "İşlem Gecikmesi (saniye)",
        "setting_delay_desc": "Otomatik kabul/reddetmeden önce bu kadar saniye bekle",
        "setting_whitelist": "Beyaz Liste (takma adlar)",
        "setting_whitelist_desc": "Bu takma adlardan gelen istekleri her zaman kabul et (satır başına bir tane)",
        "setting_blacklist": "Kara Liste (takma adlar)",
        "setting_blacklist_desc": "Bu takma adlardan gelen istekleri her zaman reddet (satır başına bir tane)",
        "setting_custom_code": "Özel Python Kodu",
        "setting_custom_code_desc": "Gelişmiş: 'accept', 'decline' veya 'manual' döndüren Python kodu",
        "setting_log_actions": "İşlemleri Bildir",
        "setting_log_actions_desc": "Otomatik kabul/reddetme durumunda bildirim göster",
        "setting_min_age": "Minimum İstek Yaşı (saniye)",
        "setting_min_age_desc": "Sadece bundan eski istekleri otomatik işle (0 = anında)",
        "setting_pattern_whitelist": "Beyaz Liste Regex Deseni",
        "setting_pattern_whitelist_desc": "Kabul edilecek takma adları eşleştirmek için regex deseni (boş = devre dışı)",
        "setting_pattern_blacklist": "Kara Liste Regex Deseni",
        "setting_pattern_blacklist_desc": "Reddedilecek takma adları eşleştirmek için regex deseni (boş = devre dışı)",

        "cmd_autoaccept_desc": "Otomatik kabul modunu aç/kapat",
        "cmd_autoaccept_usage": "/autoaccept [on|off]",
        "cmd_autorules_desc": "Mevcut otomatik yanıt kurallarını göster",
        "cmd_autorules_usage": "/autorules",

        "auto_accepted": "✅ {alias} adlı kişiden istek otomatik kabul edildi",
        "auto_declined": "❌ {alias} adlı kişiden istek otomatik reddedildi",
        "auto_accept_on": "Otomatik kabul modu etkinleştirildi",
        "auto_accept_off": "Otomatik kabul modu devre dışı (manuel mod)",
        "rules_header": "📋 Otomatik Yanıt Kuralları:",
        "rules_mode": "Varsayılan işlem: {mode}",
        "rules_delay": "Gecikme: {delay}s",
        "rules_whitelist": "Beyaz liste: {list}",
        "rules_blacklist": "Kara liste: {list}",
        "rules_pattern_wl": "Beyaz liste deseni: {pattern}",
        "rules_pattern_bl": "Kara liste deseni: {pattern}",
        "rules_custom": "Özel kod: {status}",
        "code_error": "⚠️ Özel kod hatası: {error}",
        "none": "(yok)",
        "active": "aktif",
        "inactive": "pasif",
    },
    "de": {
        "setting_enabled": "Auto-Antwort Aktiviert",
        "setting_enabled_desc": "Automatische Bearbeitung von Chat-Anfragen aktivieren",
        "setting_mode": "Standardaktion",
        "setting_mode_desc": "Was mit Anfragen geschehen soll, die keiner Regel entsprechen",
        "mode_manual": "Manuell (Fragen)",
        "mode_accept": "Auto Akzeptieren",
        "mode_decline": "Auto Ablehnen",
        "setting_delay": "Aktionsverzögerung (Sekunden)",
        "setting_delay_desc": "So viele Sekunden warten vor Auto-Akzeptieren/Ablehnen",
        "setting_whitelist": "Whitelist (Aliase)",
        "setting_whitelist_desc": "Anfragen von diesen Aliasen immer akzeptieren (einer pro Zeile)",
        "setting_blacklist": "Blacklist (Aliase)",
        "setting_blacklist_desc": "Anfragen von diesen Aliasen immer ablehnen (einer pro Zeile)",
        "setting_custom_code": "Benutzerdefinierter Python-Code",
        "setting_custom_code_desc": "Erweitert: Python-Code, der 'accept', 'decline' oder 'manual' zurückgibt",
        "setting_log_actions": "Aktionen Protokollieren",
        "setting_log_actions_desc": "Benachrichtigungen beim Auto-Akzeptieren/Ablehnen anzeigen",
        "setting_min_age": "Minimales Anfragesalter (Sekunden)",
        "setting_min_age_desc": "Nur Anfragen automatisch bearbeiten, die älter sind als dies (0 = sofort)",
        "setting_pattern_whitelist": "Whitelist Regex-Muster",
        "setting_pattern_whitelist_desc": "Regex-Muster zum Abgleichen von zu akzeptierenden Aliasen (leer = deaktiviert)",
        "setting_pattern_blacklist": "Blacklist Regex-Muster",
        "setting_pattern_blacklist_desc": "Regex-Muster zum Abgleichen von abzulehnenden Aliasen (leer = deaktiviert)",

        "cmd_autoaccept_desc": "Auto-Akzeptieren-Modus umschalten",
        "cmd_autoaccept_usage": "/autoaccept [on|off]",
        "cmd_autorules_desc": "Aktuelle Auto-Antwort-Regeln anzeigen",
        "cmd_autorules_usage": "/autorules",

        "auto_accepted": "✅ Anfrage von {alias} automatisch akzeptiert",
        "auto_declined": "❌ Anfrage von {alias} automatisch abgelehnt",
        "auto_accept_on": "Auto-Akzeptieren-Modus aktiviert",
        "auto_accept_off": "Auto-Akzeptieren-Modus deaktiviert (manueller Modus)",
        "rules_header": "📋 Auto-Antwort-Regeln:",
        "rules_mode": "Standardaktion: {mode}",
        "rules_delay": "Verzögerung: {delay}s",
        "rules_whitelist": "Whitelist: {list}",
        "rules_blacklist": "Blacklist: {list}",
        "rules_pattern_wl": "Whitelist-Muster: {pattern}",
        "rules_pattern_bl": "Blacklist-Muster: {pattern}",
        "rules_custom": "Benutzerdefinierter Code: {status}",
        "code_error": "⚠️ Benutzerdefinierter Code-Fehler: {error}",
        "none": "(keine)",
        "active": "aktiv",
        "inactive": "inaktiv",
    },
    "es": {
        "setting_enabled": "Auto-Respuesta Activada",
        "setting_enabled_desc": "Habilitar manejo automático de solicitudes de chat",
        "setting_mode": "Acción Predeterminada",
        "setting_mode_desc": "Qué hacer con solicitudes que no coinciden con ninguna regla",
        "mode_manual": "Manual (Preguntar)",
        "mode_accept": "Auto Aceptar",
        "mode_decline": "Auto Rechazar",
        "setting_delay": "Retraso de Acción (segundos)",
        "setting_delay_desc": "Esperar estos segundos antes de auto-aceptar/rechazar",
        "setting_whitelist": "Lista Blanca (alias)",
        "setting_whitelist_desc": "Siempre aceptar solicitudes de estos alias (uno por línea)",
        "setting_blacklist": "Lista Negra (alias)",
        "setting_blacklist_desc": "Siempre rechazar solicitudes de estos alias (uno por línea)",
        "setting_custom_code": "Código Python Personalizado",
        "setting_custom_code_desc": "Avanzado: Código Python que devuelve 'accept', 'decline' o 'manual'",
        "setting_log_actions": "Registrar Acciones",
        "setting_log_actions_desc": "Mostrar notificaciones al auto-aceptar/rechazar",
        "setting_min_age": "Edad Mínima de Solicitud (segundos)",
        "setting_min_age_desc": "Solo auto-procesar solicitudes más antiguas que esto (0 = inmediato)",
        "setting_pattern_whitelist": "Patrón Regex Lista Blanca",
        "setting_pattern_whitelist_desc": "Patrón regex para coincidir alias a aceptar (vacío = deshabilitado)",
        "setting_pattern_blacklist": "Patrón Regex Lista Negra",
        "setting_pattern_blacklist_desc": "Patrón regex para coincidir alias a rechazar (vacío = deshabilitado)",

        "cmd_autoaccept_desc": "Alternar modo auto-aceptar",
        "cmd_autoaccept_usage": "/autoaccept [on|off]",
        "cmd_autorules_desc": "Mostrar reglas actuales de auto-respuesta",
        "cmd_autorules_usage": "/autorules",

        "auto_accepted": "✅ Solicitud de {alias} auto-aceptada",
        "auto_declined": "❌ Solicitud de {alias} auto-rechazada",
        "auto_accept_on": "Modo auto-aceptar activado",
        "auto_accept_off": "Modo auto-aceptar desactivado (modo manual)",
        "rules_header": "📋 Reglas de Auto-Respuesta:",
        "rules_mode": "Acción predeterminada: {mode}",
        "rules_delay": "Retraso: {delay}s",
        "rules_whitelist": "Lista blanca: {list}",
        "rules_blacklist": "Lista negra: {list}",
        "rules_pattern_wl": "Patrón lista blanca: {pattern}",
        "rules_pattern_bl": "Patrón lista negra: {pattern}",
        "rules_custom": "Código personalizado: {status}",
        "code_error": "⚠️ Error de código personalizado: {error}",
        "none": "(ninguno)",
        "active": "activo",
        "inactive": "inactivo",
    },
    "fr": {
        "setting_enabled": "Auto-Réponse Activée",
        "setting_enabled_desc": "Activer le traitement automatique des demandes de chat",
        "setting_mode": "Action par Défaut",
        "setting_mode_desc": "Que faire avec les demandes qui ne correspondent à aucune règle",
        "mode_manual": "Manuel (Demander)",
        "mode_accept": "Auto Accepter",
        "mode_decline": "Auto Refuser",
        "setting_delay": "Délai d'Action (secondes)",
        "setting_delay_desc": "Attendre ce nombre de secondes avant d'auto-accepter/refuser",
        "setting_whitelist": "Liste Blanche (alias)",
        "setting_whitelist_desc": "Toujours accepter les demandes de ces alias (un par ligne)",
        "setting_blacklist": "Liste Noire (alias)",
        "setting_blacklist_desc": "Toujours refuser les demandes de ces alias (un par ligne)",
        "setting_custom_code": "Code Python Personnalisé",
        "setting_custom_code_desc": "Avancé: Code Python qui retourne 'accept', 'decline' ou 'manual'",
        "setting_log_actions": "Journaliser les Actions",
        "setting_log_actions_desc": "Afficher les notifications lors de l'auto-acceptation/refus",
        "setting_min_age": "Âge Minimum de Demande (secondes)",
        "setting_min_age_desc": "Traiter auto seulement les demandes plus anciennes que ceci (0 = immédiat)",
        "setting_pattern_whitelist": "Motif Regex Liste Blanche",
        "setting_pattern_whitelist_desc": "Motif regex pour correspondre aux alias à accepter (vide = désactivé)",
        "setting_pattern_blacklist": "Motif Regex Liste Noire",
        "setting_pattern_blacklist_desc": "Motif regex pour correspondre aux alias à refuser (vide = désactivé)",

        "cmd_autoaccept_desc": "Basculer le mode auto-accepter",
        "cmd_autoaccept_usage": "/autoaccept [on|off]",
        "cmd_autorules_desc": "Afficher les règles actuelles d'auto-réponse",
        "cmd_autorules_usage": "/autorules",

        "auto_accepted": "✅ Demande de {alias} auto-acceptée",
        "auto_declined": "❌ Demande de {alias} auto-refusée",
        "auto_accept_on": "Mode auto-accepter activé",
        "auto_accept_off": "Mode auto-accepter désactivé (mode manuel)",
        "rules_header": "📋 Règles d'Auto-Réponse:",
        "rules_mode": "Action par défaut: {mode}",
        "rules_delay": "Délai: {delay}s",
        "rules_whitelist": "Liste blanche: {list}",
        "rules_blacklist": "Liste noire: {list}",
        "rules_pattern_wl": "Motif liste blanche: {pattern}",
        "rules_pattern_bl": "Motif liste noire: {pattern}",
        "rules_custom": "Code personnalisé: {status}",
        "code_error": "⚠️ Erreur de code personnalisé: {error}",
        "none": "(aucun)",
        "active": "actif",
        "inactive": "inactif",
    },
}

class AutoAnswerRequestsPlugin(Plugin):

    def t(self, key: str, **kwargs) -> str:
        lang = "en"
        if self._app and hasattr(self._app, 'lang'):
            lang = self._app.lang or "en"

        if lang in TRANSLATIONS and key in TRANSLATIONS[lang]:
            template = TRANSLATIONS[lang][key]

        elif key in TRANSLATIONS.get("en", {}):
            template = TRANSLATIONS["en"][key]
        else:
            return key

        if kwargs:
            try:
                return template.format(**kwargs)
            except KeyError:
                return template
        return template

    @property
    def meta(self) -> PluginMeta:
        return PluginMeta(
            name="Auto Answer Requests",
            id="auto_answer_requests",
            version="1.0.0",
            description="Automatically accept or decline chat requests based on rules",
            author="E2E Client",
            requires_restart=False,
            tags=["automation", "requests", "productivity"]
        )

    @property
    def settings(self) -> List[PluginSetting]:
        return [
            PluginSetting(
                key="enabled",
                label=self.t("setting_enabled"),
                type=PluginSettingType.BOOLEAN,
                default=False,
                description=self.t("setting_enabled_desc")
            ),
            PluginSetting(
                key="mode",
                label=self.t("setting_mode"),
                type=PluginSettingType.SELECT,
                default="manual",
                description=self.t("setting_mode_desc"),
                options=[
                    ("manual", self.t("mode_manual")),
                    ("accept", self.t("mode_accept")),
                    ("decline", self.t("mode_decline"))
                ]
            ),
            PluginSetting(
                key="delay",
                label=self.t("setting_delay"),
                type=PluginSettingType.INTEGER,
                default=0,
                description=self.t("setting_delay_desc"),
                min_value=0,
                max_value=60
            ),
            PluginSetting(
                key="min_age",
                label=self.t("setting_min_age"),
                type=PluginSettingType.INTEGER,
                default=0,
                description=self.t("setting_min_age_desc"),
                min_value=0,
                max_value=3600
            ),
            PluginSetting(
                key="whitelist",
                label=self.t("setting_whitelist"),
                type=PluginSettingType.TEXT,
                default="",
                description=self.t("setting_whitelist_desc")
            ),
            PluginSetting(
                key="blacklist",
                label=self.t("setting_blacklist"),
                type=PluginSettingType.TEXT,
                default="",
                description=self.t("setting_blacklist_desc")
            ),
            PluginSetting(
                key="pattern_whitelist",
                label=self.t("setting_pattern_whitelist"),
                type=PluginSettingType.STRING,
                default="",
                description=self.t("setting_pattern_whitelist_desc")
            ),
            PluginSetting(
                key="pattern_blacklist",
                label=self.t("setting_pattern_blacklist"),
                type=PluginSettingType.STRING,
                default="",
                description=self.t("setting_pattern_blacklist_desc")
            ),
            PluginSetting(
                key="custom_code",
                label=self.t("setting_custom_code"),
                type=PluginSettingType.TEXT,
                default="# Available variables:\n# - peer_alias: str (alias of requester)\n# - peer_fp: str (fingerprint)\n# - received_at: int (unix timestamp)\n# - age_seconds: int (seconds since received)\n# - now: int (current unix timestamp)\n#\n# Return: 'accept', 'decline', or 'manual'\n#\n# Example:\n# if age_seconds > 3600:\n#     return 'decline'  # Decline old requests\n# return 'manual'",
                description=self.t("setting_custom_code_desc")
            ),
            PluginSetting(
                key="log_actions",
                label=self.t("setting_log_actions"),
                type=PluginSettingType.BOOLEAN,
                default=True,
                description=self.t("setting_log_actions_desc")
            ),
        ]

    def on_load(self) -> None:

        self.register_hook(HookType.ON_REQUEST_RECEIVE, self._on_request_receive)
        self.register_hook(HookType.ON_REQUEST_CLICK, self._on_request_click)

        self.register_command(
            name="autoaccept",
            callback=self._cmd_autoaccept,
            description=self.t("cmd_autoaccept_desc"),
            usage=self.t("cmd_autoaccept_usage")
        )
        self.register_command(
            name="autorules",
            callback=self._cmd_autorules,
            description=self.t("cmd_autorules_desc"),
            usage=self.t("cmd_autorules_usage")
        )

    def _get_whitelist(self) -> List[str]:
        text = self.get_setting("whitelist", "")
        return [line.strip().lower() for line in text.split("\n") if line.strip()]

    def _get_blacklist(self) -> List[str]:
        text = self.get_setting("blacklist", "")
        return [line.strip().lower() for line in text.split("\n") if line.strip()]

    def _evaluate_request(self, peer_alias: str, peer_fp: str, received_at: int) -> str:
        alias_lower = peer_alias.lower()
        now = int(time.time())
        age_seconds = now - received_at

        min_age = self.get_setting("min_age", 0)
        if age_seconds < min_age:
            return "manual"

        blacklist = self._get_blacklist()
        if alias_lower in blacklist:
            return "decline"

        whitelist = self._get_whitelist()
        if alias_lower in whitelist:
            return "accept"

        pattern_bl = self.get_setting("pattern_blacklist", "")
        if pattern_bl:
            try:
                if re.search(pattern_bl, peer_alias, re.IGNORECASE):
                    return "decline"
            except re.error:
                pass

        pattern_wl = self.get_setting("pattern_whitelist", "")
        if pattern_wl:
            try:
                if re.search(pattern_wl, peer_alias, re.IGNORECASE):
                    return "accept"
            except re.error:
                pass

        custom_code = self.get_setting("custom_code", "")
        if custom_code and not custom_code.startswith("#"):
            result = self._run_custom_code(custom_code, peer_alias, peer_fp, received_at, age_seconds, now)
            if result in ("accept", "decline", "manual"):
                return result

        return self.get_setting("mode", "manual")

    def _run_custom_code(self, code: str, peer_alias: str, peer_fp: str,
                         received_at: int, age_seconds: int, now: int) -> Optional[str]:

        local_vars = {
            "peer_alias": peer_alias,
            "peer_fp": peer_fp,
            "received_at": received_at,
            "age_seconds": age_seconds,
            "now": now,
            "re": re,
            "time": time,
        }

        try:

            if "return " in code:

                wrapped = f"def _eval():\n"
                for line in code.split("\n"):
                    wrapped += f"    {line}\n"
                wrapped += "_result = _eval()"
                exec(wrapped, {"re": re, "time": time}, local_vars)
                return local_vars.get("_result")
            else:

                exec(code, {"re": re, "time": time}, local_vars)
                return local_vars.get("result")
        except Exception as e:
            if self.get_setting("log_actions", True):
                self.notify(self.t("code_error", error=str(e)), severity="warning")
            return None

    async def _on_request_receive(self, request_data: Dict[str, Any]) -> Optional[str]:
        if not self.get_setting("enabled", False):
            return None

        peer_alias = request_data.get("peer_alias", "")
        peer_fp = request_data.get("peer_fp", "")
        received_at = request_data.get("received_at", int(time.time()))

        action = self._evaluate_request(peer_alias, peer_fp, received_at)

        if action == "manual":
            return None

        delay = self.get_setting("delay", 0)
        if delay > 0:
            import asyncio
            await asyncio.sleep(delay)

        if self.get_setting("log_actions", True):
            if action == "accept":
                self.notify(self.t("auto_accepted", alias=peer_alias))
            elif action == "decline":
                self.notify(self.t("auto_declined", alias=peer_alias))

        return action

    async def _on_request_click(self, request_data: Dict[str, Any]) -> Optional[str]:
        if not self.get_setting("enabled", False):
            return None

        peer_alias = request_data.get("peer_alias", "")
        peer_fp = request_data.get("peer_fp", "")
        received_at = request_data.get("received_at", int(time.time()))

        action = self._evaluate_request(peer_alias, peer_fp, received_at)

        if action == "manual":
            return None

        if self.get_setting("log_actions", True):
            if action == "accept":
                self.notify(self.t("auto_accepted", alias=peer_alias))
            elif action == "decline":
                self.notify(self.t("auto_declined", alias=peer_alias))

        return action

    async def _cmd_autoaccept(self, args: str) -> None:
        args = args.strip().lower()

        if args == "on":
            self.set_setting("enabled", True)
            self.set_setting("mode", "accept")
            self.notify(self.t("auto_accept_on"))
        elif args == "off":
            self.set_setting("enabled", False)
            self.set_setting("mode", "manual")
            self.notify(self.t("auto_accept_off"))
        else:

            enabled = self.get_setting("enabled", False)
            mode = self.get_setting("mode", "manual")

            if enabled and mode == "accept":
                self.set_setting("enabled", False)
                self.set_setting("mode", "manual")
                self.notify(self.t("auto_accept_off"))
            else:
                self.set_setting("enabled", True)
                self.set_setting("mode", "accept")
                self.notify(self.t("auto_accept_on"))

    async def _cmd_autorules(self, args: str) -> None:
        lines = [self.t("rules_header")]

        mode = self.get_setting("mode", "manual")
        mode_text = self.t(f"mode_{mode}")
        lines.append(f"  {self.t('rules_mode', mode=mode_text)}")

        delay = self.get_setting("delay", 0)
        lines.append(f"  {self.t('rules_delay', delay=delay)}")

        whitelist = self._get_whitelist()
        wl_text = ", ".join(whitelist) if whitelist else self.t("none")
        lines.append(f"  {self.t('rules_whitelist', list=wl_text)}")

        blacklist = self._get_blacklist()
        bl_text = ", ".join(blacklist) if blacklist else self.t("none")
        lines.append(f"  {self.t('rules_blacklist', list=bl_text)}")

        pattern_wl = self.get_setting("pattern_whitelist", "")
        lines.append(f"  {self.t('rules_pattern_wl', pattern=pattern_wl or self.t('none'))}")

        pattern_bl = self.get_setting("pattern_blacklist", "")
        lines.append(f"  {self.t('rules_pattern_bl', pattern=pattern_bl or self.t('none'))}")

        custom = self.get_setting("custom_code", "")
        has_custom = custom and not custom.startswith("#")
        status = self.t("active") if has_custom else self.t("inactive")
        lines.append(f"  {self.t('rules_custom', status=status)}")

        self.notify("\n".join(lines), timeout=10)
