#!/usr/bin/env python3
"""
Structured logfmt logger for CAST.AI MCP Server.

Provides structured logging in logfmt format (key=value pairs) for better
compatibility with Loki/Grafana and consistency with CAST.AI's Go services.
"""

import sys
from datetime import datetime


def _format_logfmt_value(value) -> str:
    """
    Format a value for logfmt output.

    Quotes strings that contain spaces, quotes, or special characters.
    Leaves simple values unquoted.

    Args:
        value: The value to format

    Returns:
        Formatted string value for logfmt
    """
    # Convert to string
    str_value = str(value)

    # Quote if contains spaces, quotes, equals signs, or special chars
    if ' ' in str_value or '"' in str_value or '=' in str_value or '\n' in str_value:
        # Escape quotes and backslashes
        str_value = str_value.replace('\\', '\\\\').replace('"', '\\"')
        return f'"{str_value}"'

    return str_value


class StructuredLogger:
    """Simple logfmt logger for structured logging."""

    def __init__(self, service_name: str = "castai-mcp-external"):
        self.service_name = service_name

    def log(self, level: str, message: str, **kwargs):
        """Log a message in logfmt format (key=value pairs)."""
        timestamp = datetime.utcnow().isoformat() + "Z"

        # Build logfmt line with core fields
        parts = [
            f'time="{timestamp}"',
            f'level={level.lower()}',
            f'msg="{message}"',
            f'service={self.service_name}',
        ]

        # Add additional fields
        for key, value in kwargs.items():
            formatted_value = _format_logfmt_value(value)
            parts.append(f'{key}={formatted_value}')

        # Print to stderr for visibility
        print(' '.join(parts), file=sys.stderr, flush=True)

    def info(self, message: str, **kwargs):
        """Log info message."""
        self.log("INFO", message, **kwargs)

    def error(self, message: str, **kwargs):
        """Log error message."""
        self.log("ERROR", message, **kwargs)

    def warning(self, message: str, **kwargs):
        """Log warning message."""
        self.log("WARNING", message, **kwargs)

    def debug(self, message: str, **kwargs):
        """Log debug message."""
        self.log("DEBUG", message, **kwargs)


# Global logger instance
logger = StructuredLogger("castai-mcp-external")
