# Copyright 2024 Klira AI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""LangChain adapter.

Patches use OTel context directly, eliminating detached span issues.
Suppresses LangSmith tracing.
"""

from __future__ import annotations

import logging
import os
from typing import Any, Callable

from klira.sdk.adapters.base_framework import BaseFrameworkAdapter

logger = logging.getLogger(__name__)


class LangChainAdapter(BaseFrameworkAdapter):
    """Adapter for LangChain."""

    @property
    def framework_name(self) -> str:
        return "langchain"

    def adapt_workflow(self, func: Callable[..., Any]) -> Callable[..., Any]:
        return func

    def adapt_agent(self, func: Callable[..., Any]) -> Callable[..., Any]:
        return func

    def adapt_tool(self, func: Callable[..., Any]) -> Callable[..., Any]:
        """Must preserve callability (Learning #12)."""
        return func

    def adapt_task(self, func: Callable[..., Any]) -> Callable[..., Any]:
        return func

    def patch_framework(self) -> None:
        """Suppress LangSmith tracing (unless user explicitly enabled it)."""
        existing = os.environ.get("LANGCHAIN_TRACING_V2")
        os.environ.setdefault("LANGCHAIN_TRACING_V2", "false")
        if existing and existing.lower() == "true":
            logger.info(
                "LANGCHAIN_TRACING_V2 already set to '%s' — preserving user setting",
                existing,
            )
        else:
            logger.debug("LangSmith tracing disabled")

    def verify_suppression(self) -> bool:
        """Verify LangSmith tracing is disabled."""
        return os.environ.get("LANGCHAIN_TRACING_V2", "").lower() != "true"
