"""observability.logging — Structured logging setup."""
from __future__ import annotations
import json
import logging
import sys
import time
from agentpaas.config import settings


class JSONFormatter(logging.Formatter):
    def format(self, record):
        log = {
            "timestamp": self.formatTime(record),
            "level": record.levelname,
            "service": "agentpaas",
            "message": record.getMessage(),
            "module": record.module,
        }
        if hasattr(record, 'tenant_id'):
            log["tenant_id"] = record.tenant_id
        if hasattr(record, 'agent_id'):
            log["agent_id"] = record.agent_id
        if hasattr(record, 'trace_id'):
            log["trace_id"] = record.trace_id
        if record.exc_info:
            log["exception"] = self.formatException(record.exc_info)
        return json.dumps(log, ensure_ascii=False)


def setup_logging():
    logger = logging.getLogger("agentpaas")
    logger.setLevel(getattr(logging, settings.log_level.upper(), logging.INFO))
    handler = logging.StreamHandler(sys.stdout)
    if settings.log_format == "json":
        handler.setFormatter(JSONFormatter())
    else:
        handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
    logger.addHandler(handler)
    return logger

logger = setup_logging()
