"""OTel initialization — called at app startup"""

import logging

logger = logging.getLogger(__name__)


def setup_telemetry(app, config: dict | None = None):
    """Initialize OpenTelemetry if installed and configured.

    This is a no-op when:
    - config is None or config.enabled is False
    - opentelemetry packages are not installed

    Args:
        app: FastAPI application instance
        config: Telemetry configuration dict with keys:
            - enabled (bool): Whether to enable telemetry
            - service_name (str): Service name for OTel resource
            - otlp_endpoint (str): OTLP gRPC endpoint URL
            - export_traces (bool): Whether to export traces
            - export_metrics (bool): Whether to export metrics
    """
    if not config or not config.get("enabled", False):
        logger.info("Telemetry disabled")
        return

    try:
        from opentelemetry import trace, metrics
        from opentelemetry.sdk.trace import TracerProvider
        from opentelemetry.sdk.trace.export import BatchSpanProcessor
        from opentelemetry.sdk.metrics import MeterProvider
        from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
        from opentelemetry.sdk.resources import Resource
    except ImportError:
        logger.warning(
            "OpenTelemetry packages not installed. Telemetry disabled."
        )
        return

    service_name = config.get("service_name", "fischer-agentkit")
    resource = Resource.create({"service.name": service_name})

    # Tracing setup
    if config.get("export_traces", True):
        endpoint = config.get("otlp_endpoint", "http://localhost:4317")
        try:
            from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
                OTLPSpanExporter,
            )

            provider = TracerProvider(resource=resource)
            provider.add_span_processor(
                BatchSpanProcessor(
                    OTLPSpanExporter(endpoint=endpoint, insecure=True)
                )
            )
            trace.set_tracer_provider(provider)
            logger.info(f"Tracing enabled, exporting to {endpoint}")
        except ImportError:
            logger.warning(
                "OTLP exporter not installed. Tracing disabled."
            )

    # Metrics setup
    if config.get("export_metrics", True):
        endpoint = config.get("otlp_endpoint", "http://localhost:4317")
        try:
            from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
                OTLPMetricExporter,
            )

            reader = PeriodicExportingMetricReader(
                OTLPMetricExporter(endpoint=endpoint, insecure=True)
            )
            provider = MeterProvider(resource=resource, readers=[reader])
            metrics.set_meter_provider(provider)
            logger.info(f"Metrics enabled, exporting to {endpoint}")
        except ImportError:
            logger.warning(
                "OTLP metric exporter not installed. Metrics disabled."
            )

    # FastAPI auto-instrumentation
    try:
        from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

        FastAPIInstrumentor.instrument_app(app, excluded_urls="health,metrics")
        logger.info("FastAPI auto-instrumentation enabled")
    except ImportError:
        logger.warning(
            "FastAPI instrumentation not installed. Skipping auto-instrumentation."
        )
