"""Structured logging helpers."""

from __future__ import annotations

import json
import logging
import os
import sys
from typing import Any, Dict

_LOGGER_NAME = "azure_discovery"


def _build_json_formatter() -> logging.Formatter:
    class JsonFormatter(logging.Formatter):
        def format(self, record: logging.LogRecord) -> str:
            payload: Dict[str, Any] = {
                "logger": record.name,
                "level": record.levelname,
                "message": record.getMessage(),
                "module": record.module,
                "function": record.funcName,
            }
            if record.exc_info:
                payload["exc_info"] = self.formatException(record.exc_info)
            if record.__dict__.get("context"):
                payload["context"] = record.__dict__["context"]
            return json.dumps(payload)

    return JsonFormatter()


def get_logger(quiet: bool = False) -> logging.Logger:
    """Return module-wide structured logger.

    Args:
        quiet: If True, only log ERROR and above. Logs always go to stderr.
    """

    logger = logging.getLogger(_LOGGER_NAME)
    if logger.handlers:
        # Update log level if quiet mode changed
        if quiet:
            logger.setLevel(logging.ERROR)
        return logger

    # Always use stderr for logs, never stdout
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(_build_json_formatter())
    logger.addHandler(handler)

    if quiet:
        logger.setLevel(logging.ERROR)
    else:
        env_level = os.getenv("AZURE_DISCOVERY_LOG_LEVEL", "INFO").upper()
        logger.setLevel(env_level)

    logger.propagate = False
    return logger
