"""Django integration — middleware and authentication signal hooks.

Installation in ``settings.py``::

    MIDDLEWARE = [
        ...
        'kanban_analytics.integrations.django.AnalyticsMiddleware',
    ]

Usage in views::

    def my_view(request):
        request.analytics.track('page_viewed', properties={'path': request.path})
"""

from __future__ import annotations

import logging
from typing import Any, Callable

logger = logging.getLogger("kanban_analytics.integrations.django")


# ---------------------------------------------------------------------------
# Django middleware
# ---------------------------------------------------------------------------


class AnalyticsMiddleware:
    """Attach a request-scoped analytics client to every Django request.

    Automatically includes the authenticated user's ID when available.
    """

    def __init__(self, get_response: Callable[..., Any]) -> None:
        self.get_response = get_response

    def __call__(self, request: Any) -> Any:
        from kanban_analytics import analytics

        user_id: str | None = None
        if hasattr(request, "user") and hasattr(request.user, "is_authenticated"):
            try:
                if request.user.is_authenticated:
                    user_id = str(request.user.pk)
            except Exception:
                pass

        request.analytics = analytics.with_context(
            user_id=user_id,
            request_id=getattr(request, "request_id", None),
        )

        response = self.get_response(request)
        return response


# ---------------------------------------------------------------------------
# Django auth signal hooks
# ---------------------------------------------------------------------------


def connect_auth_signals(auto_track: bool = True) -> None:
    """Automatically track Django authentication events.

    Call in ``AppConfig.ready()``::

        class MyAppConfig(AppConfig):
            def ready(self):
                from kanban_analytics.integrations.django import connect_auth_signals
                connect_auth_signals()
    """
    if not auto_track:
        return

    try:
        from django.contrib.auth.signals import (
            user_logged_in,
            user_logged_out,
            user_login_failed,
        )
    except ImportError:
        logger.warning(
            "django.contrib.auth not available — auth signal tracking disabled"
        )
        return

    from kanban_analytics import analytics

    def on_login(sender: Any, request: Any, user: Any, **kwargs: Any) -> None:
        analytics.track(
            "user_logged_in",
            user_id=str(user.pk),
            await_response=False,
        )

    def on_logout(sender: Any, request: Any, user: Any, **kwargs: Any) -> None:
        if user is not None:
            analytics.track(
                "user_logged_out",
                user_id=str(user.pk),
                await_response=False,
            )

    def on_login_failed(
        sender: Any, credentials: Any, request: Any, **kwargs: Any
    ) -> None:
        analytics.track(
            "user_login_failed",
            anonymous_id="django_auth",
            properties={"username": credentials.get("username", "unknown")},
            await_response=False,
        )

    user_logged_in.connect(on_login, dispatch_uid="kanban_login")
    user_logged_out.connect(on_logout, dispatch_uid="kanban_logout")
    user_login_failed.connect(
        on_login_failed, dispatch_uid="kanban_login_failed"
    )
