"""Flask integration — extension that attaches analytics to ``g``.

Usage::

    from flask import Flask, g
    from kanban_analytics.integrations.flask import AnalyticsExtension

    app = Flask(__name__)
    analytics_ext = AnalyticsExtension()
    analytics_ext.init_app(app)

    @app.route('/')
    def index():
        g.analytics.track('page_viewed', properties={'path': '/'})
        return 'OK'
"""

from __future__ import annotations

from typing import Any


class AnalyticsExtension:
    """Flask extension for analytics tracking.

    Call :meth:`init_app` with a Flask application to register
    ``before_request`` / ``teardown_request`` hooks that attach a
    scoped :class:`~kanban_analytics.ScopedAnalyticsClient` to
    ``flask.g.analytics``.
    """

    def __init__(self, app: Any | None = None) -> None:
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Any) -> None:
        """Register hooks on *app*."""
        app.before_request(self._before_request)
        app.teardown_request(self._teardown_request)

    @staticmethod
    def _before_request() -> None:
        from flask import g as flask_g
        from flask import request as flask_request

        from kanban_analytics import analytics

        user_id: str | None = None
        try:
            # flask-login compatibility
            from flask_login import current_user  # type: ignore[import-untyped]

            if current_user and current_user.is_authenticated:
                user_id = str(current_user.id)
        except Exception:
            pass

        flask_g.analytics = analytics.with_context(user_id=user_id)

    @staticmethod
    def _teardown_request(exc: Exception | None) -> None:
        # Placeholder for future cleanup if needed
        pass
