"""LangChain callback handler for logging observability."""
from __future__ import annotations

import logging
from typing import Any

from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult

logger = logging.getLogger(__name__)


class LoggingCallbackHandler(BaseCallbackHandler):
    """Route LangChain events to Python logging for observability."""

    def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> None:
        provider = serialized.get("id", ["unknown"])[-1]
        logger.info("llm_call_start provider=%s", provider)

    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
        token_usage = {}
        if response.llm_output:
            token_usage = response.llm_output.get("token_usage", {})
        logger.info("llm_call_end tokens=%s", token_usage)

    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
        logger.error("llm_call_error error=%s", error)
