# ruff: noqa: F821
from __future__ import annotations

import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from router import Event

class Module:
    config = {
        "enabled": {"type": "boolean", "label": {"ru": "Автоответы включены", "en": "Enable automatic replies"}, "default": False},
        "pattern": {"type": "string", "label": {"ru": "Входящий текст", "en": "Incoming text"}, "default": "", "max": 256},
        "matching": {"type": "select", "label": {"ru": "Сравнение", "en": "Matching"}, "choices": ["equals", "contains"], "default": "equals"},
        "reply": {"type": "string", "label": {"ru": "Ответ", "en": "Reply"}, "default": "", "max": 4000},
        "cooldown": {"type": "integer", "label": {"ru": "Пауза между ответами в одном чате, секунд", "en": "Cooldown per chat, seconds"}, "min": 30, "max": 86400, "default": 300},
    }

    @loader.handler(source="both", access="public")
    async def respond(self, ctx: Event) -> dict:
        config = await app.config.all()
        if not config.get("enabled") or ctx.data.get("out") or not ctx.text or ctx.chat_id is None: return {"sent": False}
        pattern, text, reply = config.get("pattern", "").casefold(), ctx.text.casefold(), config.get("reply", "")
        if not pattern or not reply: return {"sent": False}
        matches = text == pattern if config.get("matching") == "equals" else pattern in text
        if not matches: return {"sent": False}
        key = f"cooldown/{ctx.source}/{ctx.chat_id}"
        now = time.time()
        if await app.db.get(key, default=0) > now: return {"sent": False}
        await app.db.set(key, now + config["cooldown"], ttl=86400)
        await ctx.reply(reply)
        return {"sent": True}
