"""
Langfuse client singleton with safe no-op behavior.
"""
from __future__ import annotations

from typing import Any, Dict, Optional

from app.core.config import settings

try:
    from langfuse import Langfuse
except Exception:  # pragma: no cover
    Langfuse = None  # type: ignore[assignment]


class _NoOpClient:
    def trace(self, *args: Any, **kwargs: Any) -> "_NoOpTrace":
        return _NoOpTrace()

    def flush(self) -> None:
        return None


class _NoOpTrace:
    def span(self, *args: Any, **kwargs: Any) -> "_NoOpSpan":
        return _NoOpSpan()

    def generation(self, *args: Any, **kwargs: Any) -> "_NoOpSpan":
        return _NoOpSpan()

    def update(self, *args: Any, **kwargs: Any) -> None:
        return None

    def score(self, *args: Any, **kwargs: Any) -> None:
        return None

    def end(self, *args: Any, **kwargs: Any) -> None:
        return None


class _NoOpSpan(_NoOpTrace):
    pass


def _create_langfuse_client() -> Any:
    if not bool(getattr(settings, "ENABLE_LANGFUSE", False)):
        return _NoOpClient()
    public_key = (settings.LANGFUSE_PUBLIC_KEY or "").strip()
    secret_key = (settings.LANGFUSE_SECRET_KEY or "").strip()
    host = (settings.LANGFUSE_HOST or "https://cloud.langfuse.com").strip()
    if not public_key or not secret_key or Langfuse is None:
        return _NoOpClient()
    try:
        return Langfuse(public_key=public_key, secret_key=secret_key, host=host)
    except Exception:
        return _NoOpClient()


langfuse = _create_langfuse_client()

