"""
Unicode-safe logging setup
"""

import logging
import sys

_GLYPHS = {
    "->": "->",
    "<-": "<-",
    "—": "-",
    "–": "-",
    "…": "...",
    """: '"', """: '"',
    "'": "'",
    "⇒": "=>",
    "⇐": "<=",
    "<->": "<->",
    "⇔": "<=>",
    "•": "*",
    "×": "x",
    "÷": "/",
    "≈": "~=",
    "≠": "!=",
    "≤": "<=",
    "≥": ">=",
    "∞": "inf",
    "✓": "OK",
    "✗": "FAIL",
    "✔": "[Y]",
    "✘": "[N]",
    "⚠": "WARN",
    "⚡": "(!)",
    "🔍": "[search]",
    "📊": "[stats]",
}


class AsciiSanitizer(logging.Filter):
    """Replace fancy glyphs with ASCII equivalents"""

    def filter(self, record: logging.LogRecord) -> bool:
        msg = record.getMessage()
        for k, v in _GLYPHS.items():
            msg = msg.replace(k, v)
        record.msg, record.args = msg, ()
        return True


def setup_logging(level=logging.INFO) -> logging.Logger:
    """Configure logging with Unicode safety"""
    root = logging.getLogger()
    root.handlers.clear()
    root.setLevel(level)

    h = logging.StreamHandler(stream=sys.stdout)
    h.addFilter(AsciiSanitizer())
    h.setFormatter(
        logging.Formatter(
            "%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )
    )
    root.addHandler(h)
    return root
