"""Instrumentation demo (Ketju spans + third-party spans).

This example shows how an application can:
1) configure a tracer provider/exporter
2) enable third-party instrumentation (LlamaIndex)
3) run Ketju code that emits spans which become parents of lower-level spans

Run:
  uv sync --extra rag --extra observability
  uv run python -m ketju.examples.instrumentation_demo
"""

from __future__ import annotations

from pathlib import Path

from ketju.config import DOCS_DIR, DATA_DIR
from ketju.core.instrumentation import instrument_ketju


def _configure_console_tracing(service_name: str = "ketju-demo") -> bool:
    """Configure a console span exporter (demo-friendly).

    This is intentionally kept in the example (app-level concern).
    """

    try:
        from opentelemetry import trace  # type: ignore
        from opentelemetry.sdk.resources import Resource  # type: ignore
        from opentelemetry.sdk.trace import TracerProvider  # type: ignore
        from opentelemetry.sdk.trace.export import (  # type: ignore
            BatchSpanProcessor,
            ConsoleSpanExporter,
        )
    except ModuleNotFoundError:
        return False

    provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
    provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
    trace.set_tracer_provider(provider)
    return True


def _pick_one_pdf() -> Path | None:
    pdfs = list(DOCS_DIR.glob("**/*.pdf"))
    return pdfs[0] if pdfs else None


def main() -> None:
    ok = _configure_console_tracing(service_name="ketju-instrumentation-demo")
    if not ok:
        raise SystemExit(
            "OpenTelemetry SDK not installed.\n"
            "Install with: uv sync --extra observability"
        )

    # Enable third-party instrumentation hooks (opt-in).
    instrument_ketju(
        service_name="ketju-instrumentation-demo",
        enable_logfire=False,
        instrument_pydantic_ai=False,
        instrument_llamaindex=True,
    )

    pdf = _pick_one_pdf()
    if not pdf:
        raise SystemExit(f"No PDFs found under {DOCS_DIR}. Add a PDF under docs/ and rerun.")

    from ketju.rag.llama_index.variants.simple import SimplePdfRag

    rag = SimplePdfRag(name="demo_simple_pdf", persist_dir=DATA_DIR / "demo_simple_pdf")
    rag.ingest(files=[pdf], max_files=1)
    print(rag.query("What is this document about?"))


if __name__ == "__main__":
    main()

