"""Auto-detect and instrument known AI agent frameworks via OpenInference."""

from __future__ import annotations

import importlib
import logging

logger = logging.getLogger(__name__)

_KNOWN: list[tuple[str, str, str]] = [
    ("langchain",   "openinference.instrumentation.langchain",   "LangChainInstrumentor"),
    ("llama_index", "openinference.instrumentation.llama_index", "LlamaIndexInstrumentor"),
    ("crewai",      "openinference.instrumentation.crewai",      "CrewAIInstrumentor"),
    ("haystack",    "openinference.instrumentation.haystack",    "HaystackInstrumentor"),
]


def auto_instrument(frameworks: list[str] | None = None) -> list[str]:
    """Try to instrument known frameworks. Returns list of instrumented names.

    Args:
        frameworks: If given, only try these framework names.
                    If None, try all known frameworks.
    """
    instrumented: list[str] = []

    for name, module_path, class_name in _KNOWN:
        if frameworks is not None and name not in frameworks:
            continue
        try:
            mod = importlib.import_module(module_path)
            instrumentor_cls = getattr(mod, class_name)
            instrumentor_cls().instrument()
            instrumented.append(name)
            logger.info("Instrumented %s", name)
        except ImportError:
            logger.debug("Skipping %s (instrumentor not installed)", name)
        except Exception:
            logger.warning("Failed to instrument %s", name, exc_info=True)

    return instrumented
