"""Structured JSON logging configuration.

In **production** (``AEGIS_ENV=production``), emits one JSON object per
line so that log aggregators (ELK, CloudWatch, Datadog) can ingest them
without custom parsing.

In **development** (default), uses a human-readable text format for
comfortable local work.
"""

# Enable future language features for compatibility
from __future__ import annotations

# Import json
import json

# Import logging
import logging

# Import os
import os

# Import sys
import sys

# Import datetime, timezone from datetime
from datetime import datetime, timezone


# Define class _JSONFormatter
class _JSONFormatter(logging.Formatter):
    """Emit each log record as a single-line JSON object."""

    # Define function format
    def format(self, record: logging.LogRecord) -> str:
        # Assign payload = {
        payload: dict = {
            # Literal argument value
            "timestamp": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(),
            # Literal argument value
            "level": record.levelname,
            # Literal argument value
            "logger": record.name,
            # Literal argument value
            "message": record.getMessage(),
        }

        # Check: record.exc_info and record.exc_info[1] is not None
        if record.exc_info and record.exc_info[1] is not None:
            # Assign payload["exception"] = self.formatException(record.exc_info)
            payload["exception"] = self.formatException(record.exc_info)

        # Assign extra = getattr(record, "_extra", None)
        extra = getattr(record, "_extra", None)
        # Check: extra
        if extra:
            # Call payload.update()
            payload.update(extra)

        # Return json.dumps(payload, default=str)
        return json.dumps(payload, default=str)


# Assign _DEV_FORMAT = "%(asctime)s  %(levelname)-8s  %(name)s — %(message)s"
_DEV_FORMAT = "%(asctime)s  %(levelname)-8s  %(name)s — %(message)s"


# Define function setup_logging
def setup_logging() -> None:
    """Configure the root logger based on the environment."""
    # Assign is_production = os.environ.get("AEGIS_ENV", "").lower() == "production"
    is_production = os.environ.get("AEGIS_ENV", "").lower() == "production"
    # Assign level_name = os.environ.get("LOG_LEVEL", "INFO").upper()
    level_name = os.environ.get("LOG_LEVEL", "INFO").upper()
    # Assign level = getattr(logging, level_name, logging.INFO)
    level = getattr(logging, level_name, logging.INFO)

    # Assign root = logging.getLogger()
    root = logging.getLogger()
    # Call root.setLevel()
    root.setLevel(level)

    # Check: root.handlers
    if root.handlers:
        # Call root.handlers.clear()
        root.handlers.clear()

    # Assign handler = logging.StreamHandler(sys.stdout)
    handler = logging.StreamHandler(sys.stdout)
    # Call handler.setLevel()
    handler.setLevel(level)

    # Check: is_production
    if is_production:
        # Call handler.setFormatter()
        handler.setFormatter(_JSONFormatter())
    # Fallback: handle remaining cases
    else:
        # Call handler.setFormatter()
        handler.setFormatter(logging.Formatter(_DEV_FORMAT))

    # Call root.addHandler()
    root.addHandler(handler)

    # Call logging.getLogger()
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    # Call logging.getLogger()
    logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
