"""FastAPI integration — dependency injection and lifespan helpers.

Usage::

    from fastapi import Depends, FastAPI
    from typing import Annotated
    from contextlib import asynccontextmanager
    from kanban_analytics import async_analytics
    from kanban_analytics.integrations.fastapi import get_analytics, Analytics

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        await async_analytics.init('your-api-key', endpoint='https://…/api/ingest')
        yield
        await async_analytics.shutdown()

    app = FastAPI(lifespan=lifespan)

    @app.post('/checkout')
    async def checkout(analytics: Analytics):
        await analytics.track('checkout_initiated')
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from typing import Annotated

    from fastapi import Depends

    from ..async_client import AsyncScopedAnalyticsClient


async def get_analytics(request: Any) -> Any:
    """FastAPI dependency that provides a request-scoped async analytics client.

    Extracts user identity from ``request.state.user_id`` if set by
    an auth dependency earlier in the chain.

    Usage with ``Depends``::

        from fastapi import Depends
        from kanban_analytics.integrations.fastapi import get_analytics

        @app.post('/checkout')
        async def checkout(analytics=Depends(get_analytics)):
            await analytics.track('checkout_initiated')
    """
    from kanban_analytics import async_analytics

    user_id: str | None = getattr(request.state, "user_id", None)
    request_id: str | None = request.headers.get("X-Request-ID")

    return async_analytics.with_context(
        user_id=user_id,
        request_id=request_id,
    )


# Convenience type alias — import and use as a type annotation:
#
#     from kanban_analytics.integrations.fastapi import Analytics
#
#     async def my_endpoint(analytics: Analytics):
#         await analytics.track('endpoint_called')
#
# We define this at module level so it is importable, but keep actual
# framework imports behind TYPE_CHECKING to avoid hard dependencies.
try:
    from typing import Annotated

    from fastapi import Depends

    from ..async_client import AsyncScopedAnalyticsClient

    Analytics = Annotated[AsyncScopedAnalyticsClient, Depends(get_analytics)]
except ImportError:
    Analytics = Any  # type: ignore[assignment,misc]
