# 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.

"""Framework detection — cached with lru_cache for thread safety."""

from __future__ import annotations

import importlib
import logging
import sys
from functools import lru_cache

logger = logging.getLogger(__name__)

# Framework detection order (most specific first)
_FRAMEWORK_CHECKS: list[tuple[str, str]] = [
    ("openai_agents", "agents"),
    ("crewai", "crewai"),
    ("langchain", "langchain"),
    ("langgraph", "langgraph"),
    ("llamaindex", "llama_index"),
]


@lru_cache(maxsize=256)
def detect_framework() -> str:
    """Detect which AI framework is in use.

    Returns the framework name string. Defaults to "standard" if
    no specific framework is detected.

    Cached via lru_cache for performance (thread-safe in CPython).
    """
    for name, module_name in _FRAMEWORK_CHECKS:
        if module_name in sys.modules:
            logger.debug("Detected framework: %s (module: %s)", name, module_name)
            return name
        try:
            importlib.import_module(module_name)
            logger.debug("Detected framework: %s (importable: %s)", name, module_name)
            return name
        except ImportError:
            continue

    return "standard"


def clear_detection_cache() -> None:
    """Clear the framework detection cache (for testing)."""
    detect_framework.cache_clear()
