"""Configure logging to stdout with format driven by LOG_FORMAT env var."""

import json
import logging
import os
import sys
from datetime import datetime, timezone


class JsonFormatter(logging.Formatter):
    """Formatter that outputs one JSON object per line."""

    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "level": record.levelname,
            "name": record.name,
            "message": record.getMessage(),
        }
        if record.exc_info:
            payload["exc_info"] = self.formatException(record.exc_info)
        return json.dumps(payload)


def configure_logging(
    logger_name: str = "stax_sdk",
    level: int = logging.INFO,
) -> None:
    """
    Configure logging to stdout. Format is controlled by LOG_FORMAT env var:
    - LOG_FORMAT=json (case-insensitive): one JSON object per line
    - Otherwise: human-readable format
    """
    log_format_env = os.environ.get("LOG_FORMAT", "").strip().lower()
    use_json = log_format_env == "json"

    logger = logging.getLogger(logger_name)
    logger.setLevel(level)
    # Avoid duplicate handlers if called multiple times
    if logger.handlers:
        return
    handler = logging.StreamHandler(sys.stdout)
    if use_json:
        handler.setFormatter(JsonFormatter())
    else:
        handler.setFormatter(
            logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        )
    logger.addHandler(handler)
