import os
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.langchain import LangchainInstrumentor
from opentelemetry.instrumentation.aiokafka import AIOKafkaInstrumentor 

def activate_open_telemetry(app, settings):
    """
    Activa OpenTelemetry si la configuración lo permite.
    """
    if not settings.otel_config.OTEL_ENABLED:
        return

    resource = Resource.create(attributes={
        "service.name": settings.otel_config.OTEL_SERVICE_NAME
    })

    trace.set_tracer_provider(TracerProvider(resource=resource))
    
    otlp_exporter = OTLPSpanExporter(
        endpoint=settings.otel_config.OTEL_EXPORTER_OTLP_ENDPOINT,
        insecure=True
    )
    
    trace.get_tracer_provider().add_span_processor(
        BatchSpanProcessor(otlp_exporter)
    )

    FastAPIInstrumentor.instrument_app(app)

    LangchainInstrumentor().instrument()

    # Instrumentar Kafka (Si el agente usa mensajería)
    AIOKafkaInstrumentor().instrument() 
    
    print(f"OpenTelemetry activado para: {settings.otel_config.OTEL_SERVICE_NAME}")