
from plugins import Plugin, PluginMeta, PluginSetting, PluginSettingType, HookType
from typing import Optional
import time

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

        "setting_show_deleted": "Show Deleted Messages",
        "setting_show_deleted_desc": "Show deleted messages in red instead of hiding them",
        "setting_show_edit_history": "Show Edit History",
        "setting_show_edit_history_desc": "Show indicator for edited messages with history",
        "setting_deleted_style": "Deleted Message Style",
        "setting_deleted_style_desc": "How to display deleted messages",
        "style_red_strike": "Red + Strikethrough",
        "style_red_dim": "Red + Dimmed",
        "style_red_only": "Red Only",
        "style_strike_only": "Strikethrough Only",
        "setting_history_indicator": "History Indicator",
        "setting_history_indicator_desc": "Button text to expand edit history",
        "setting_history_collapse": "Collapse Indicator",
        "setting_history_collapse_desc": "Button text to collapse edit history",
        "setting_deleted_indicator": "Deleted Indicator",
        "setting_deleted_indicator_desc": "Marker shown for deleted messages (emoji supported)",
        "setting_max_versions": "Max History Versions",
        "setting_max_versions_desc": "Maximum number of edit versions to store per message",

        "ctx_view_history": "📜 View Edit History",
        "cmd_history_desc": "View message edit history",
        "cmd_history_usage": "/history <message_id>",
        "cmd_deleted_desc": "List deleted messages in current chat",
        "cmd_deleted_usage": "/deleted",
        "cmd_clear_desc": "Clear all stored history data",
        "cmd_clear_usage": "/clearhistory",
        "cmd_find_desc": "Search messages with regex pattern",
        "cmd_find_usage": "/find <regex_pattern>",

        "no_chat_selected": "No chat selected",
        "no_edit_history": "No edit history available for this message",
        "no_deleted_messages": "No deleted messages recorded in this chat",
        "no_data_to_clear": "No data to clear",
        "cleared_data": "Cleared {deleted} deleted messages and {versions} edit versions",
        "stats_info": "📊 Deleted: {deleted} | Edited: {edited} ({versions} versions)",

        "find_no_pattern": "Please provide a regex pattern. Usage: /find <pattern>",
        "find_invalid_regex": "Invalid regex pattern: {error}",
        "find_no_matches": "No messages found matching: {pattern}",
        "find_mode_enter": "🔍 Find mode: {current}/{total} | [Enter] Next | [Esc] Exit",
        "find_mode_exit": "Exited find mode",

        "dialog_edit_history": "Edit History ({count} versions)",
        "dialog_deleted_messages": "Deleted Messages",
        "edit_history_header": "Edit history (oldest to newest):",
        "version_label": "Version {num} ({time})",
        "deleted_in_chat": "Deleted messages in this chat ({count}):",
        "unknown_time": "Unknown time",
        "btn_close": "Close",
    },
    "tr": {

        "setting_show_deleted": "Silinen Mesajları Göster",
        "setting_show_deleted_desc": "Silinen mesajları gizlemek yerine kırmızı göster",
        "setting_show_edit_history": "Düzenleme Geçmişini Göster",
        "setting_show_edit_history_desc": "Geçmişi olan düzenlenmiş mesajlar için gösterge göster",
        "setting_deleted_style": "Silinen Mesaj Stili",
        "setting_deleted_style_desc": "Silinen mesajları nasıl göstereceğini seç",
        "style_red_strike": "Kırmızı + Üstü Çizili",
        "style_red_dim": "Kırmızı + Soluk",
        "style_red_only": "Sadece Kırmızı",
        "style_strike_only": "Sadece Üstü Çizili",
        "setting_history_indicator": "Geçmiş Göstergesi",
        "setting_history_indicator_desc": "Düzenleme geçmişini açma butonu metni",
        "setting_history_collapse": "Daraltma Göstergesi",
        "setting_history_collapse_desc": "Düzenleme geçmişini daraltma butonu metni",
        "setting_deleted_indicator": "Silinen Göstergesi",
        "setting_deleted_indicator_desc": "Silinen mesajlar için gösterilen işaret (emoji destekli)",
        "setting_max_versions": "Maks Geçmiş Sürümü",
        "setting_max_versions_desc": "Mesaj başına saklanacak maksimum düzenleme sürümü",

        "ctx_view_history": "📜 Düzenleme Geçmişini Gör",
        "cmd_history_desc": "Mesaj düzenleme geçmişini gör",
        "cmd_history_usage": "/history <mesaj_id>",
        "cmd_deleted_desc": "Bu sohbetteki silinen mesajları listele",
        "cmd_deleted_usage": "/deleted",
        "cmd_clear_desc": "Tüm kayıtlı geçmiş verilerini temizle",
        "cmd_clear_usage": "/clearhistory",
        "cmd_find_desc": "Regex deseniyle mesaj ara",
        "cmd_find_usage": "/find <regex_deseni>",

        "no_chat_selected": "Sohbet seçilmedi",
        "no_edit_history": "Bu mesaj için düzenleme geçmişi yok",
        "no_deleted_messages": "Bu sohbette kaydedilmiş silinen mesaj yok",
        "no_data_to_clear": "Temizlenecek veri yok",
        "cleared_data": "{deleted} silinen mesaj ve {versions} düzenleme sürümü temizlendi",
        "stats_info": "📊 Silinen: {deleted} | Düzenlenen: {edited} ({versions} sürüm)",

        "find_no_pattern": "Lütfen bir regex deseni girin. Kullanım: /find <desen>",
        "find_invalid_regex": "Geçersiz regex deseni: {error}",
        "find_no_matches": "Eşleşen mesaj bulunamadı: {pattern}",
        "find_mode_enter": "🔍 Arama modu: {current}/{total} | [Enter] Sonraki | [Esc] Çık",
        "find_mode_exit": "Arama modundan çıkıldı",

        "dialog_edit_history": "Düzenleme Geçmişi ({count} sürüm)",
        "dialog_deleted_messages": "Silinen Mesajlar",
        "edit_history_header": "Düzenleme geçmişi (eskiden yeniye):",
        "version_label": "Sürüm {num} ({time})",
        "deleted_in_chat": "Bu sohbetteki silinen mesajlar ({count}):",
        "unknown_time": "Bilinmeyen zaman",
        "btn_close": "Kapat",
    },
    "de": {
        "setting_show_deleted": "Gelöschte Nachrichten Anzeigen",
        "setting_show_deleted_desc": "Gelöschte Nachrichten rot anzeigen statt zu verstecken",
        "setting_show_edit_history": "Bearbeitungsverlauf Anzeigen",
        "setting_show_edit_history_desc": "Indikator für bearbeitete Nachrichten mit Verlauf anzeigen",
        "setting_deleted_style": "Stil Gelöschter Nachrichten",
        "setting_deleted_style_desc": "Wie gelöschte Nachrichten angezeigt werden sollen",
        "style_red_strike": "Rot + Durchgestrichen",
        "style_red_dim": "Rot + Abgedunkelt",
        "style_red_only": "Nur Rot",
        "style_strike_only": "Nur Durchgestrichen",
        "setting_history_indicator": "Verlaufs-Indikator",
        "setting_history_indicator_desc": "Button-Text zum Erweitern des Bearbeitungsverlaufs",
        "setting_history_collapse": "Einklappen-Indikator",
        "setting_history_collapse_desc": "Button-Text zum Einklappen des Bearbeitungsverlaufs",
        "setting_deleted_indicator": "Gelöscht-Indikator",
        "setting_deleted_indicator_desc": "Markierung für gelöschte Nachrichten (Emoji unterstützt)",
        "setting_max_versions": "Max Verlaufsversionen",
        "setting_max_versions_desc": "Maximale Anzahl der zu speichernden Bearbeitungsversionen pro Nachricht",

        "ctx_view_history": "📜 Bearbeitungsverlauf Anzeigen",
        "cmd_history_desc": "Nachricht-Bearbeitungsverlauf anzeigen",
        "cmd_history_usage": "/history <nachricht_id>",
        "cmd_deleted_desc": "Gelöschte Nachrichten im aktuellen Chat auflisten",
        "cmd_deleted_usage": "/deleted",
        "cmd_clear_desc": "Alle gespeicherten Verlaufsdaten löschen",
        "cmd_clear_usage": "/clearhistory",
        "cmd_find_desc": "Nachrichten mit Regex-Muster suchen",
        "cmd_find_usage": "/find <regex_muster>",

        "no_chat_selected": "Kein Chat ausgewählt",
        "no_edit_history": "Kein Bearbeitungsverlauf für diese Nachricht verfügbar",
        "no_deleted_messages": "Keine gelöschten Nachrichten in diesem Chat aufgezeichnet",
        "no_data_to_clear": "Keine Daten zum Löschen",
        "cleared_data": "{deleted} gelöschte Nachrichten und {versions} Bearbeitungsversionen gelöscht",
        "stats_info": "📊 Gelöscht: {deleted} | Bearbeitet: {edited} ({versions} Versionen)",

        "find_no_pattern": "Bitte geben Sie ein Regex-Muster an. Verwendung: /find <muster>",
        "find_invalid_regex": "Ungültiges Regex-Muster: {error}",
        "find_no_matches": "Keine Nachrichten gefunden für: {pattern}",
        "find_mode_enter": "🔍 Suchmodus: {current}/{total} | [Enter] Nächste | [Esc] Beenden",
        "find_mode_exit": "Suchmodus beendet",

        "dialog_edit_history": "Bearbeitungsverlauf ({count} Versionen)",
        "dialog_deleted_messages": "Gelöschte Nachrichten",
        "edit_history_header": "Bearbeitungsverlauf (älteste bis neueste):",
        "version_label": "Version {num} ({time})",
        "deleted_in_chat": "Gelöschte Nachrichten in diesem Chat ({count}):",
        "unknown_time": "Unbekannte Zeit",
        "btn_close": "Schließen",
    },
    "es": {
        "setting_show_deleted": "Mostrar Mensajes Eliminados",
        "setting_show_deleted_desc": "Mostrar mensajes eliminados en rojo en lugar de ocultarlos",
        "setting_show_edit_history": "Mostrar Historial de Edición",
        "setting_show_edit_history_desc": "Mostrar indicador para mensajes editados con historial",
        "setting_deleted_style": "Estilo de Mensaje Eliminado",
        "setting_deleted_style_desc": "Cómo mostrar los mensajes eliminados",
        "style_red_strike": "Rojo + Tachado",
        "style_red_dim": "Rojo + Atenuado",
        "style_red_only": "Solo Rojo",
        "style_strike_only": "Solo Tachado",
        "setting_history_indicator": "Indicador de Historial",
        "setting_history_indicator_desc": "Texto del botón para expandir el historial de edición",
        "setting_history_collapse": "Indicador de Colapsar",
        "setting_history_collapse_desc": "Texto del botón para colapsar el historial de edición",
        "setting_deleted_indicator": "Indicador de Eliminado",
        "setting_deleted_indicator_desc": "Marcador para mensajes eliminados (emoji soportado)",
        "setting_max_versions": "Máx Versiones de Historial",
        "setting_max_versions_desc": "Número máximo de versiones de edición a almacenar por mensaje",

        "ctx_view_history": "📜 Ver Historial de Edición",
        "cmd_history_desc": "Ver historial de edición del mensaje",
        "cmd_history_usage": "/history <id_mensaje>",
        "cmd_deleted_desc": "Listar mensajes eliminados en el chat actual",
        "cmd_deleted_usage": "/deleted",
        "cmd_clear_desc": "Borrar todos los datos de historial almacenados",
        "cmd_clear_usage": "/clearhistory",
        "cmd_find_desc": "Buscar mensajes con patrón regex",
        "cmd_find_usage": "/find <patrón_regex>",

        "no_chat_selected": "Ningún chat seleccionado",
        "no_edit_history": "No hay historial de edición disponible para este mensaje",
        "no_deleted_messages": "No hay mensajes eliminados registrados en este chat",
        "no_data_to_clear": "No hay datos para borrar",
        "cleared_data": "Borrados {deleted} mensajes eliminados y {versions} versiones de edición",
        "stats_info": "📊 Eliminados: {deleted} | Editados: {edited} ({versions} versiones)",

        "find_no_pattern": "Por favor proporciona un patrón regex. Uso: /find <patrón>",
        "find_invalid_regex": "Patrón regex inválido: {error}",
        "find_no_matches": "No se encontraron mensajes para: {pattern}",
        "find_mode_enter": "🔍 Modo búsqueda: {current}/{total} | [Enter] Siguiente | [Esc] Salir",
        "find_mode_exit": "Salió del modo búsqueda",

        "dialog_edit_history": "Historial de Edición ({count} versiones)",
        "dialog_deleted_messages": "Mensajes Eliminados",
        "edit_history_header": "Historial de edición (más antiguo a más reciente):",
        "version_label": "Versión {num} ({time})",
        "deleted_in_chat": "Mensajes eliminados en este chat ({count}):",
        "unknown_time": "Hora desconocida",
        "btn_close": "Cerrar",
    },
    "fr": {
        "setting_show_deleted": "Afficher les Messages Supprimés",
        "setting_show_deleted_desc": "Afficher les messages supprimés en rouge au lieu de les cacher",
        "setting_show_edit_history": "Afficher l'Historique d'Édition",
        "setting_show_edit_history_desc": "Afficher l'indicateur pour les messages modifiés avec historique",
        "setting_deleted_style": "Style de Message Supprimé",
        "setting_deleted_style_desc": "Comment afficher les messages supprimés",
        "style_red_strike": "Rouge + Barré",
        "style_red_dim": "Rouge + Atténué",
        "style_red_only": "Rouge Seulement",
        "style_strike_only": "Barré Seulement",
        "setting_history_indicator": "Indicateur d'Historique",
        "setting_history_indicator_desc": "Texte du bouton pour développer l'historique d'édition",
        "setting_history_collapse": "Indicateur de Réduction",
        "setting_history_collapse_desc": "Texte du bouton pour réduire l'historique d'édition",
        "setting_deleted_indicator": "Indicateur de Suppression",
        "setting_deleted_indicator_desc": "Marqueur pour les messages supprimés (emoji supporté)",
        "setting_max_versions": "Max Versions d'Historique",
        "setting_max_versions_desc": "Nombre maximum de versions d'édition à stocker par message",

        "ctx_view_history": "📜 Voir l'Historique d'Édition",
        "cmd_history_desc": "Voir l'historique d'édition du message",
        "cmd_history_usage": "/history <id_message>",
        "cmd_deleted_desc": "Lister les messages supprimés dans le chat actuel",
        "cmd_deleted_usage": "/deleted",
        "cmd_clear_desc": "Effacer toutes les données d'historique stockées",
        "cmd_clear_usage": "/clearhistory",
        "cmd_find_desc": "Rechercher des messages avec un motif regex",
        "cmd_find_usage": "/find <motif_regex>",

        "no_chat_selected": "Aucun chat sélectionné",
        "no_edit_history": "Aucun historique d'édition disponible pour ce message",
        "no_deleted_messages": "Aucun message supprimé enregistré dans ce chat",
        "no_data_to_clear": "Aucune donnée à effacer",
        "cleared_data": "Effacé {deleted} messages supprimés et {versions} versions d'édition",
        "stats_info": "📊 Supprimés: {deleted} | Modifiés: {edited} ({versions} versions)",

        "find_no_pattern": "Veuillez fournir un motif regex. Usage: /find <motif>",
        "find_invalid_regex": "Motif regex invalide: {error}",
        "find_no_matches": "Aucun message trouvé pour: {pattern}",
        "find_mode_enter": "🔍 Mode recherche: {current}/{total} | [Entrée] Suivant | [Échap] Quitter",
        "find_mode_exit": "Sorti du mode recherche",

        "dialog_edit_history": "Historique d'Édition ({count} versions)",
        "dialog_deleted_messages": "Messages Supprimés",
        "edit_history_header": "Historique d'édition (du plus ancien au plus récent):",
        "version_label": "Version {num} ({time})",
        "deleted_in_chat": "Messages supprimés dans ce chat ({count}):",
        "unknown_time": "Heure inconnue",
        "btn_close": "Fermer",
    },
}

class MessageHistoryPlugin(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]:
            try:
                val = TRANSLATIONS[lang][key]
                return val.format(**kwargs) if kwargs else val
            except (KeyError, ValueError):
                return TRANSLATIONS[lang][key]

        if "en" in TRANSLATIONS and key in TRANSLATIONS["en"]:
            try:
                val = TRANSLATIONS["en"][key]
                return val.format(**kwargs) if kwargs else val
            except (KeyError, ValueError):
                return TRANSLATIONS["en"][key]

        return key

    @property
    def translations(self) -> dict[str, dict[str, str]]:
        return TRANSLATIONS

    @property
    def meta(self) -> PluginMeta:
        return PluginMeta(
            name="Message History",
            id="message_history",
            version="1.0.0",
            description="Shows deleted messages in red and preserves edit history with expandable panels",
            author="ANTCH",
            requires_restart=False,
            tags=["messages", "history", "privacy", "deleted", "edited"]
        )

    @property
    def settings(self) -> list[PluginSetting]:
        return [
            PluginSetting(
                key="show_deleted",
                label=self.t("setting_show_deleted"),
                type=PluginSettingType.BOOLEAN,
                default=True,
                description=self.t("setting_show_deleted_desc")
            ),
            PluginSetting(
                key="show_edit_history",
                label=self.t("setting_show_edit_history"),
                type=PluginSettingType.BOOLEAN,
                default=True,
                description=self.t("setting_show_edit_history_desc")
            ),
            PluginSetting(
                key="deleted_style",
                label=self.t("setting_deleted_style"),
                type=PluginSettingType.SELECT,
                default="red_strike",
                options=[
                    ("red_strike", self.t("style_red_strike")),
                    ("red_dim", self.t("style_red_dim")),
                    ("red_only", self.t("style_red_only")),
                    ("strike_only", self.t("style_strike_only")),
                ],
                description=self.t("setting_deleted_style_desc")
            ),
            PluginSetting(
                key="history_indicator",
                label=self.t("setting_history_indicator"),
                type=PluginSettingType.STRING,
                default="◀",
                placeholder="◀ ▶ ► ◄",
                description=self.t("setting_history_indicator_desc")
            ),
            PluginSetting(
                key="history_collapse",
                label=self.t("setting_history_collapse"),
                type=PluginSettingType.STRING,
                default="▼",
                placeholder="▼ ▲ △ ▽",
                description=self.t("setting_history_collapse_desc")
            ),
            PluginSetting(
                key="deleted_indicator",
                label=self.t("setting_deleted_indicator"),
                type=PluginSettingType.STRING,
                default="[X]",
                placeholder="🗑️ ❌ [X]",
                description=self.t("setting_deleted_indicator_desc")
            ),
            PluginSetting(
                key="max_history_versions",
                label=self.t("setting_max_versions"),
                type=PluginSettingType.INTEGER,
                default=10,
                description=self.t("setting_max_versions_desc"),
                min_value=1,
                max_value=50
            ),
        ]

    @property
    def css(self) -> str:
        return """
        .msg-history-panel {
            background: $surface;
            border-left: thick $warning;
            padding: 0 1;
            margin: 1 0 1 2;
        }
        .msg-history-header {
            color: $text-muted;
            text-style: italic;
        }
        .msg-history-content {
            color: $text;
            padding-left: 1;
        }
        .msg-history-time {
            color: $text-muted;
            text-style: dim;
        }
        """

    def __init__(self):
        super().__init__()

        self._expanded_history: dict[str, bool] = {}

        self._history_cache: dict[str, list[dict]] = {}

        self._deleted_cache: set[str] = set()
        self._deleted_cache_loaded: bool = False

        self._db_initialized = False

    def _init_database(self) -> None:
        if self._db_initialized:
            return

        self.plugin_db_create_table("deleted_messages", {
            "msg_id": "TEXT PRIMARY KEY",
            "chat_id": "TEXT",
            "sender": "TEXT",
            "content": "TEXT",
            "original_ts": "REAL",
            "deleted_at": "REAL"
        })

        self.plugin_db_create_table("edit_history", {
            "id": "TEXT PRIMARY KEY",
            "msg_id": "TEXT",
            "content": "TEXT",
            "edited_at": "REAL"
        })

        self._db_initialized = True
        self.log("Database initialized")

    def on_load(self) -> None:
        self.log("Message History plugin loaded!")

        self._init_database()

        self._load_deleted_cache()

        self.register_command(
            name="history",
            callback=self.cmd_history,
            description=self.t("cmd_history_desc"),
            usage=self.t("cmd_history_usage")
        )

        self.register_command(
            name="deleted",
            callback=self.cmd_deleted,
            description=self.t("cmd_deleted_desc"),
            usage=self.t("cmd_deleted_usage")
        )

        self.register_command(
            name="clearhistory",
            callback=self.cmd_clear_history,
            description=self.t("cmd_clear_desc"),
            usage=self.t("cmd_clear_usage")
        )

    def on_enable(self) -> None:
        self.log("Message History enabled")
        if self.css:
            self.inject_css(self.css)

    def on_disable(self) -> None:
        self.log("Message History disabled")
        self.remove_css()

    def on_settings_changed(self, settings: dict) -> None:
        self.log(f"Settings changed: {settings}")

        if self._app and hasattr(self._app, 'refresh_messages'):
            try:
                self._app.refresh_messages()
            except Exception:
                pass

    def on_message_render(self, message: str, sender: str, meta: dict) -> Optional[dict]:
        message_id = meta.get("id", "")

        is_deleted = meta.get("_deleted", False) or (message_id and self._is_message_deleted(message_id))

        if is_deleted:
            if self.get_setting("show_deleted", True):
                return self._render_deleted_message(message, meta)
            return {"text": "", "hidden": True}

        return None

    def _render_deleted_message(self, message: str, meta: dict) -> dict:
        from rich.markup import escape as markup_escape

        style = self.get_setting("deleted_style", "red_strike")
        indicator = self.get_setting("deleted_indicator", "🗑️")

        css_classes = ["msg-deleted"]
        if style == "red_strike":
            css_classes.append("msg-deleted-strike")
        elif style == "red_dim":
            css_classes.append("msg-deleted-dim")
        elif style == "strike_only":
            css_classes.append("msg-deleted-strike")
            css_classes.remove("msg-deleted")

        safe_message = markup_escape(message)

        return {
            "text": f"{indicator} {safe_message}",
            "css_classes": css_classes
        }

    def get_history_count(self, message_id: str) -> int:
        if not message_id:
            return 0
        try:
            self._init_database()
            count = self.plugin_db_count("edit_history", "msg_id = ?", (message_id,))
            return int(count)
        except Exception:
            return 0

    def _mark_message_deleted(self, message_id: str, chat_id: str = "", content: str = "", sender: str = "", original_ts: float = 0) -> None:
        self._init_database()

        self.plugin_db_insert("deleted_messages", {
            "msg_id": message_id,
            "chat_id": chat_id,
            "sender": sender,
            "content": content,
            "original_ts": original_ts,
            "deleted_at": time.time()
        })
        self._deleted_cache.add(message_id)
        self.log(f"Marked message {message_id} as deleted")

    def _load_deleted_cache(self) -> None:
        if self._deleted_cache_loaded:
            return
        self._init_database()
        try:
            rows = self.plugin_db_select("deleted_messages")
            self._deleted_cache = {r.get("msg_id") for r in rows if r.get("msg_id")}
            self._deleted_cache_loaded = True
        except Exception:
            self._deleted_cache = set()

    def _is_message_deleted(self, message_id: str) -> bool:
        if not message_id:
            return False

        self._load_deleted_cache()
        return message_id in self._deleted_cache

    def _get_deleted_message(self, message_id: str) -> Optional[dict]:
        if not message_id:
            return None
        self._init_database()

        rows = self.plugin_db_select("deleted_messages", "msg_id = ?", (message_id,), limit=1)
        rows = [r for r in rows if r.get("msg_id") == message_id]
        return rows[0] if rows else None

    def _get_deleted_messages_for_chat(self, chat_id: str, limit: int = 50) -> list[dict]:
        if not chat_id:
            return []
        self._init_database()

        rows = self.plugin_db_select(
            "deleted_messages",
            "chat_id = ?",
            (chat_id,),
            limit=0
        )

        rows = [r for r in rows if r.get("chat_id") == chat_id]

        rows.sort(key=lambda x: x.get("deleted_at", 0), reverse=True)
        if limit > 0:
            rows = rows[:limit]
        return rows

    def _store_message_version(self, message_id: str, content: str, timestamp: float = None) -> None:
        import uuid
        self._init_database()

        edit_ts = timestamp or time.time()
        self.plugin_db_insert("edit_history", {
            "id": f"{message_id}_{edit_ts}_{uuid.uuid4().hex[:8]}",
            "msg_id": message_id,
            "content": content,
            "edited_at": edit_ts
        })

        if message_id in self._history_cache:
            del self._history_cache[message_id]

        max_versions = self.get_setting("max_history_versions", 10)
        count = self.plugin_db_count("edit_history", "msg_id = ?", (message_id,))

        if count > max_versions:

            all_versions = self.plugin_db_select("edit_history", "msg_id = ?", (message_id,))

            all_versions.sort(key=lambda x: x.get("edited_at", 0), reverse=True)
            versions_to_delete = all_versions[max_versions:]
            for v in versions_to_delete:
                if v.get("id"):
                    self.plugin_db_delete("edit_history", "id = ?", (v["id"],))

        self.log(f"Stored edit version for message {message_id}")

    def _get_message_history(self, message_id: str) -> list[dict]:
        if not message_id:
            return []

        self._init_database()

        rows = self.plugin_db_select(
            "edit_history",
            "msg_id = ?",
            (message_id,)
        )


        rows = [r for r in rows if r.get("msg_id") == message_id]

        rows.sort(key=lambda x: x.get("edited_at", 0))

        history = [
            {"content": row["content"], "timestamp": row["edited_at"]}
            for row in rows
        ]

        return history

    def _get_stats(self) -> dict:
        self._init_database()

        return {
            "deleted_count": self.plugin_db_count("deleted_messages"),
            "edit_versions_count": self.plugin_db_count("edit_history"),
            "unique_edited_messages": len(set(
                row["msg_id"] for row in self.plugin_db_select("edit_history")
            ))
        }

    def record_edit(self, message_id: str, old_content: str, timestamp: float = None) -> None:
        if self.get_setting("show_edit_history", True):
            self._store_message_version(message_id, old_content, timestamp)

    def record_delete(self, message_id: str, chat_id: str = "", content: str = "", sender: str = "", original_ts: float = 0) -> bool:
        if self.get_setting("show_deleted", True):
            self._mark_message_deleted(message_id, chat_id, content, sender, original_ts)
            return True
        return False

    def toggle_history(self, message_id: str) -> bool:
        current = self._expanded_history.get(message_id, False)
        self._expanded_history[message_id] = not current
        return not current

    def show_message_history_dialog(self, message_data: dict) -> None:
        from rich.markup import escape as markup_escape

        message_id = message_data.get("id", "")
        history = self._get_message_history(message_id)

        if not history:
            self.notify(self.t("no_edit_history"), severity="warning")
            return

        content_lines = [self.t("edit_history_header") + "\n"]
        for i, version in enumerate(history):
            timestamp = version.get("timestamp", 0)
            content = version.get("content", "")

            if timestamp:
                from datetime import datetime
                dt = datetime.fromtimestamp(timestamp)
                time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
            else:
                time_str = self.t("unknown_time")

            content_lines.append(f"─── {self.t('version_label', num=i + 1, time=time_str)} ───")
            content_lines.append(markup_escape(content))
            content_lines.append("")

        self.show_dialog(
            title=self.t("dialog_edit_history", count=len(history)),
            content="\n".join(content_lines),
            buttons=[(self.t("btn_close"), "close")]
        )

    def cmd_history(self, args: list[str]) -> None:
        if not args:

            stats = self._get_stats()
            self.notify(
                self.t("stats_info", deleted=stats['deleted_count'], edited=stats['unique_edited_messages'], versions=stats['edit_versions_count']),
                severity="information"
            )
            return

        message_id = args[0]
        self.show_message_history_dialog({"id": message_id})

    def cmd_deleted(self, args: list[str]) -> None:
        from rich.markup import escape as markup_escape

        chat_id = self.current_chat
        if not chat_id:
            self.notify(self.t("no_chat_selected"), severity="warning")
            return

        deleted_messages = self._get_deleted_messages_for_chat(chat_id, limit=20)

        if not deleted_messages:
            self.notify(self.t("no_deleted_messages"), severity="information")
            return

        lines = [self.t("deleted_in_chat", count=len(deleted_messages)) + "\n"]

        for msg in deleted_messages:
            content = (msg.get("content") or "")[:50]
            sender = msg.get("sender", "?")
            ts = msg.get("deleted_at", 0)

            if ts:
                from datetime import datetime
                time_str = datetime.fromtimestamp(ts).strftime("%H:%M:%S")
            else:
                time_str = "?"

            safe_content = markup_escape(content)
            safe_sender = markup_escape(sender)
            lines.append(f"• [{time_str}] {safe_sender}: {safe_content}{'...' if len(msg.get('content', '')) > 50 else ''}")

        self.show_dialog(
            title=self.t("dialog_deleted_messages"),
            content="\n".join(lines),
            buttons=[(self.t("btn_close"), "close")]
        )

    def cmd_clear_history(self, args: list[str]) -> None:
        self._init_database()

        deleted_count = self.plugin_db_count("deleted_messages")
        history_count = self.plugin_db_count("edit_history")

        if deleted_count == 0 and history_count == 0:
            self.notify(self.t("no_data_to_clear"), severity="information")
            return

        self.plugin_db_clear_table("deleted_messages")
        self.plugin_db_clear_table("edit_history")

        self._history_cache.clear()
        self._expanded_history.clear()

        self.notify(self.t("cleared_data", deleted=deleted_count, versions=history_count), severity="success")
