"""Telegram Log Handler – no local log files."""
import logging
from typing import Optional

from config.settings import LOG_BOT_TOKEN, LOG_CHAT_ID, LOG_LEVEL


class TelegramLogHandler(logging.Handler):
    def __init__(self, bot_token: str, chat_id: str, level=logging.WARNING):
        super().__init__(level=level)
        self.bot_token = bot_token
        self.chat_id = str(chat_id)
        self.api_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"

    def emit(self, record: logging.LogRecord):
        if not self.bot_token or not self.chat_id:
            return
        try:
            msg = self.format(record)
            if len(msg) > 4000:
                msg = msg[:4000] + "\n... (truncated)"

            import urllib.request, json, ssl

            data = json.dumps({
                "chat_id": self.chat_id,
                "text": f"<pre>{_escape_html(msg)}</pre>",
                "parse_mode": "HTML",
                "disable_notification": True,
            }).encode("utf-8")

            req = urllib.request.Request(
                self.api_url, data=data,
                headers={"Content-Type": "application/json"}, method="POST",
            )
            ctx = ssl.create_default_context()
            with urllib.request.urlopen(req, context=ctx, timeout=8) as resp:
                resp.read()
        except Exception:
            self.handleError(record)


def _escape_html(text: str) -> str:
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def setup_logging():
    level_map = {
        "DEBUG": logging.DEBUG, "INFO": logging.INFO,
        "WARNING": logging.WARNING, "ERROR": logging.ERROR,
        "CRITICAL": logging.CRITICAL,
    }
    tg_level = level_map.get(LOG_LEVEL, logging.WARNING)

    root = logging.getLogger()
    root.setLevel(logging.INFO)
    for h in list(root.handlers):
        root.removeHandler(h)

    console = logging.StreamHandler()
    console.setLevel(logging.WARNING)
    console.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
    root.addHandler(console)

    if LOG_BOT_TOKEN and LOG_CHAT_ID:
        tg = TelegramLogHandler(LOG_BOT_TOKEN, LOG_CHAT_ID, level=tg_level)
        tg.setFormatter(logging.Formatter("%(asctime)s | %(name)s | %(levelname)s\n%(message)s"))
        root.addHandler(tg)

    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)
    logging.getLogger("telegram").setLevel(logging.WARNING)
    logging.getLogger("aiohttp").setLevel(logging.WARNING)

    return logging.getLogger("merchant-bot")
