"""
Logging configuration with Logfire integration.

LangSmith tracing lives in `quber.agents.langsmith_tracer` and posts runs
to LangSmith's native `/runs/multipart` endpoint with explicit
`inputs`/`outputs` fields. That keeps the LangSmith UI showing actual prompts
and responses rather than empty input/output panels (the OTLP path's
schema-translation gap).
"""

import logging
import sys
from typing import Any, Optional

import logfire
from loguru import logger

from quber.settings import get_settings


def setup_logging(
    service_name: str = "quber",
    enable_logfire: bool = True,
    log_level: str = "INFO",
    suppress_external: bool = True,
) -> None:
    """
    Set up logging with loguru and optional logfire integration.

    Args:
        service_name: Name for the service in logfire
        enable_logfire: Whether to enable logfire telemetry
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
        suppress_external: Whether to suppress verbose external library logs
    """
    if suppress_external:
        logging.getLogger("docling").setLevel(logging.WARNING)
        logging.getLogger("docling.document_converter").setLevel(logging.WARNING)
        logging.getLogger("docling_core").setLevel(logging.WARNING)
        logging.getLogger("httpx").setLevel(logging.WARNING)
        logging.getLogger("httpcore").setLevel(logging.WARNING)
        logging.getLogger("anthropic").setLevel(logging.WARNING)
        logging.getLogger("openai").setLevel(logging.WARNING)
        logging.getLogger("langsmith").setLevel(logging.WARNING)

        import warnings

        warnings.filterwarnings("ignore", category=DeprecationWarning, module="docling")

    logger.remove()
    logger.add(
        sys.stderr,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level=log_level,
    )

    logfire_token = get_settings().obs.logfire_token
    if enable_logfire and logfire_token:
        try:
            logfire.configure(
                service_name=service_name,
                token=logfire_token,
                console=False,
            )
            logfire.instrument_anthropic()
            logfire.instrument_openai()
            logfire.instrument_pydantic_ai()

            if log_level == "DEBUG":
                logger.info(f"Logfire telemetry enabled for service: {service_name}")
        except Exception as e:
            logger.warning(f"Failed to configure logfire: {e}")
    else:
        if not logfire_token:
            logger.debug("Logfire token not found, telemetry disabled")


def get_logger(name: Optional[str] = None) -> Any:
    """
    Get a logger instance.

    Args:
        name: Optional name for the logger context

    Returns:
        Logger instance
    """
    if name:
        return logger.bind(context=name)
    return logger
