"""Structured logging configuration for AgentKit.

Provides JSON-formatted structured logs using Python's built-in logging module.
No external dependencies required.
"""

import json
import logging
from datetime import datetime, timezone
from typing import Any


class StructuredFormatter(logging.Formatter):
    """JSON structured log formatter.

    Outputs each log record as a single-line JSON object with standard fields
    (timestamp, level, logger, message) plus optional structured fields
    (trace_id, agent_name, skill_name, task_id).
    """

    def format(self, record: logging.LogRecord) -> str:
        log_entry: dict[str, Any] = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "level": record.levelname,
            "logger": record.name,
            "message": record.getMessage(),
        }

        # Add optional structured fields from LogRecord extras
        for key in ("trace_id", "agent_name", "skill_name", "task_id"):
            value = getattr(record, key, None)
            if value:
                log_entry[key] = value

        # Add exception info
        if record.exc_info and record.exc_info[1]:
            log_entry["exception"] = self.formatException(record.exc_info)

        return json.dumps(log_entry, ensure_ascii=False)


def setup_structured_logging(level: int = logging.INFO) -> None:
    """Configure structured JSON logging for the agentkit namespace.

    Replaces all existing handlers on the ``agentkit`` logger with a single
    :class:`StructuredFormatter`-backed stream handler.
    """
    root_logger = logging.getLogger("agentkit")
    root_logger.setLevel(level)

    # Remove existing handlers to avoid duplicate output
    root_logger.handlers.clear()

    handler = logging.StreamHandler()
    handler.setFormatter(StructuredFormatter())
    root_logger.addHandler(handler)


def get_logger(name: str, **extra: Any) -> logging.LoggerAdapter:
    """Get a logger with extra structured fields.

    The returned ``LoggerAdapter`` automatically injects *extra* keyword
    arguments into every log record so they appear in the JSON output.
    """
    logger = logging.getLogger(f"agentkit.{name}")
    return logging.LoggerAdapter(logger, extra)
