from aiogram import BaseMiddleware

class BapMiddleware3(BaseMiddleware):
    """
    TeleAds middleware for aiogram 3.

    This middleware integrates TeleAds SDK with your aiogram bot to track user activity
    and handle advertisement updates automatically.
    """

    def __init__(self, api_key: str) -> None:
        """
        Initialize the TeleAds middleware.

        Args:
            api_key: Your TeleAds API key obtained from TeleAds dashboard
        """
        self._bap = Bap(api_key)

    async def __call__(
        self,
        handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
        event: Update,
        data: Dict[str, Any]
    ) -> Any:
        """
        Process incoming updates through TeleAds SDK.

        Returns:
            Handler result if update should be processed, None if it's a TeleAds internal update
        """
        update_dict = event.model_dump(mode='json')

        should_process = await self._bap.handle_update(update_dict)

        if should_process:
            return await handler(event, data)
        else:
            # Skip processing for TeleAds internal updates
            return None

    def get_bap_instance(self) -> Bap:
        """
        Get the underlying BAP instance for manual advertisement sending.

        Returns:
            Bap instance for manual operations
        """
        return self._bap
