"""OpenTelemetry tracing — on when OTEL_EXPORTER_OTLP_ENDPOINT is set (the
standard OpenTelemetry variable; OTEL_SERVICE_NAME and the other OTEL_*
variables apply as usual). Each request becomes a trace with a span per
SQL statement and outbound HTTP call, exported over OTLP/HTTP to a
collector (Jaeger, Tempo, Honeycomb, …); JSON log lines carry the trace_id
so a log line leads to its trace."""

import logging
import os

log = logging.getLogger("flowfabric")


def setup_tracing(app) -> bool:
    if not os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
        return False
    try:
        from opentelemetry import trace
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
        from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
        from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
        from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
        from opentelemetry.sdk.resources import Resource
        from opentelemetry.sdk.trace import TracerProvider
        from opentelemetry.sdk.trace.export import BatchSpanProcessor
    except ImportError:
        log.warning("OTEL_EXPORTER_OTLP_ENDPOINT is set but the OpenTelemetry packages aren't installed — tracing is off")
        return False

    from app.core.database import engine

    provider = TracerProvider(resource=Resource.create({"service.name": os.environ.get("OTEL_SERVICE_NAME", "flowfabric-api")}))
    provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    trace.set_tracer_provider(provider)
    FastAPIInstrumentor.instrument_app(app, excluded_urls="health,ready,metrics")
    SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine)
    HTTPXClientInstrumentor().instrument()
    log.info("Tracing to %s", os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"])
    return True
