"""Structured JSONL logging for the CloudSense DX MCP server.

Writes one JSON object per line to ~/.cloudsense-dx-mcp/logs/server.jsonl.
Configurable via environment variables:
  CLOUDSENSE_DX_LOG_DIR   -- override log directory
  CLOUDSENSE_DX_LOG_LEVEL -- DEBUG (default), INFO, WARNING, ERROR
"""

import json
import logging
import os
import platform
import sys
from datetime import datetime, timezone
from logging.handlers import RotatingFileHandler
from pathlib import Path
from uuid import uuid4

_LOG_DIR_ENV = "CLOUDSENSE_DX_LOG_DIR"
_LOG_LEVEL_ENV = "CLOUDSENSE_DX_LOG_LEVEL"
_DEFAULT_LOG_DIR = Path.home() / ".cloudsense-dx-mcp" / "logs"
_LOG_FILENAME = "server.jsonl"
_MAX_BYTES = 5 * 1024 * 1024  # 5 MB
_BACKUP_COUNT = 3

SESSION_ID: str = uuid4().hex[:8]


class JsonFormatter(logging.Formatter):
    """Format each log record as a single-line JSON object."""

    def format(self, record: logging.LogRecord) -> str:
        entry: dict = {
            "ts": datetime.now(timezone.utc).isoformat(),
            "level": record.levelname,
            "thread": record.threadName,
        }
        json_fields = getattr(record, "json_fields", None)
        if json_fields:
            entry.update(json_fields)
        else:
            entry["message"] = record.getMessage()
        return json.dumps(entry, default=str)


def _get_log_dir() -> Path:
    env = os.getenv(_LOG_DIR_ENV)
    if env:
        return Path(env)
    return _DEFAULT_LOG_DIR


def get_log_file_path() -> Path:
    return _get_log_dir() / _LOG_FILENAME


def setup_logging() -> None:
    """Configure the cloudsense_dx_mcp logger with a JSONL rotating file handler."""
    log_dir = _get_log_dir()
    log_dir.mkdir(parents=True, exist_ok=True)
    log_file = log_dir / _LOG_FILENAME

    level_name = os.getenv(_LOG_LEVEL_ENV, "DEBUG").upper()
    level = getattr(logging, level_name, logging.DEBUG)

    handler = RotatingFileHandler(
        str(log_file),
        maxBytes=_MAX_BYTES,
        backupCount=_BACKUP_COUNT,
        encoding="utf-8",
    )
    handler.setFormatter(JsonFormatter())
    handler.setLevel(level)

    root_logger = logging.getLogger("cloudsense_dx_mcp")
    root_logger.setLevel(level)
    root_logger.addHandler(handler)
    # Prevent log propagation to MCP's stderr transport
    root_logger.propagate = False


def log_event(logger: logging.Logger, level: str, **fields) -> None:
    """Emit a structured JSON log entry with arbitrary key-value fields.

    Usage:
        log_event(logger, "INFO", tool="fetch_orchestration_templates", duration_s=4.2)
    """
    numeric_level = getattr(logging, level.upper(), logging.INFO)
    record = logger.makeRecord(
        name=logger.name,
        level=numeric_level,
        fn="",
        lno=0,
        msg="",
        args=(),
        exc_info=None,
    )
    record.json_fields = fields  # type: ignore[attr-defined]
    logger.handle(record)


def get_system_info() -> dict:
    """Collect system metadata for startup and diagnostics logging."""
    return {
        "os": sys.platform,
        "os_version": platform.platform(),
        "python": platform.python_version(),
        "machine": platform.machine(),
    }
