"""Logs : console + fichier tournant (10 Mo × 5) + Sentry optionnel."""
import logging
import logging.handlers

from core import config

_configured = False


def setup_logging() -> None:
    global _configured
    if _configured:
        return
    _configured = True
    fmt = logging.Formatter("%(asctime)s %(levelname)s [%(name)s] %(message)s")
    root = logging.getLogger()
    root.setLevel(config.LOG_LEVEL)
    if not any(type(h) is logging.StreamHandler for h in root.handlers):
        sh = logging.StreamHandler()
        sh.setFormatter(fmt)
        root.addHandler(sh)
    try:
        config.LOG_DIR.mkdir(parents=True, exist_ok=True)
        fh = logging.handlers.RotatingFileHandler(
            config.LOG_DIR / "meeconic.log", maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
        fh.setFormatter(fmt)
        root.addHandler(fh)
    except Exception as e:  # le service doit démarrer même si le dossier de logs est inaccessible
        root.warning("Logs fichier désactivés: %s", e)

    if config.SENTRY_DSN:
        try:
            import sentry_sdk
            sentry_sdk.init(dsn=config.SENTRY_DSN, environment=config.APP_ENV,
                            traces_sample_rate=0.0, send_default_pii=False)
            root.info("Sentry activé")
        except ImportError:
            root.warning("SENTRY_DSN défini mais sentry-sdk n'est pas installé.")
        except Exception as e:
            root.warning("Sentry non initialisé: %s", e)
