import asyncio
from app.extensions import db
from app.core.models.notification import Notification
from app.core.models.user import User, Role, Permission

class NotificationService:
    """
    Service for managing system notifications.
    Provides methods for sending notifications to specific users, roles, 
    or users with specific permissions. Supports both sync and async operations.
    """

    @staticmethod
    def _active_users_query():
        """
        Returns a base query object for active, non-deleted users.
        
        Returns:
            Query: SQLAlchemy query for active users.
        """
        return User.query_active().filter(User.is_active.is_(True))

    @staticmethod
    def get_users_by_role_names(role_names: list[str]):
        """
        Fetches active users that belong to one of the provided role names.

        Args:
            role_names (list[str]): List of role names to filter by.

        Returns:
            list[User]: List of matching User objects.
        """
        if not role_names:
            return []

        return (
            NotificationService._active_users_query()
            .join(User.role)
            .filter(Role.name.in_(role_names))
            .all()
        )

    @staticmethod
    def get_users_by_permission(permission_slug: str):
        """
        Fetches active users that have a specific permission via role mapping.

        Args:
            permission_slug (str): Slug of the permission to check.

        Returns:
            list[User]: List of matching User objects.
        """
        if not permission_slug:
            return []

        return (
            NotificationService._active_users_query()
            .join(User.role)
            .join(Role.permissions)
            .filter(Permission.slug == permission_slug)
            .all()
        )

    @staticmethod
    def get_admin_users():
        """
        Fetches active users with admin-level roles (Admin or SuperAdmin).

        Returns:
            list[User]: List of admin User objects.
        """
        return NotificationService.get_users_by_role_names(['Admin', 'SuperAdmin'])

    @staticmethod
    def send_to_users(users, title: str, message: str, link: str = None, type: str = 'info', exclude_user_ids: list = None, commit: bool = True):
        """
        Sends a notification payload to a list of users.

        Args:
            users (list): List of User objects or user UUID strings.
            title (str): Notification title.
            message (str): Notification content.
            link (str, optional): Target URL when the notification is clicked.
            type (str): Notification category ('info', 'success', 'warning', 'danger').
            exclude_user_ids (list, optional): List of user IDs to skip.
            commit (bool): Whether to commit the session immediately.

        Returns:
            int: Number of notifications successfully sent.
        """
        user_map = NotificationService._normalize_user_map(users)
        excluded = {str(uid) for uid in (exclude_user_ids or []) if uid}

        sent_count = 0
        for user_id in user_map.keys():
            if user_id in excluded:
                continue
            NotificationService.send(user_id, title, message, link=link, type=type, commit=False)
            sent_count += 1

        if commit and sent_count > 0:
            db.session.commit()

        return sent_count

    @staticmethod
    def send_to_role_names(role_names: list[str], title: str, message: str, link: str = None, type: str = 'info', exclude_user_ids: list = None, commit: bool = True):
        """
        Sends notifications to all active users belonging to the provided role names.

        Args:
            role_names (list[str]): List of target role names.
            title (str): Notification title.
            message (str): Notification content.
            link (str, optional): Target URL.
            type (str): Notification type.
            exclude_user_ids (list, optional): IDs to skip.
            commit (bool): Commit transaction.

        Returns:
            int: Number of notifications sent.
        """
        users = NotificationService.get_users_by_role_names(role_names)
        return NotificationService.send_to_users(
            users,
            title,
            message,
            link=link,
            type=type,
            exclude_user_ids=exclude_user_ids,
            commit=commit,
        )

    @staticmethod
    def send_to_admins(title: str, message: str, link: str = None, type: str = 'info', exclude_user_ids: list = None, commit: bool = True):
        """
        Sends notifications to all active admin users.

        Args:
            title (str): Notification title.
            message (str): Notification content.
            link (str, optional): Target URL.
            type (str): Notification type.
            exclude_user_ids (list, optional): IDs to skip.
            commit (bool): Commit transaction.

        Returns:
            int: Number of notifications sent.
        """
        users = NotificationService.get_admin_users()
        return NotificationService.send_to_users(
            users,
            title,
            message,
            link=link,
            type=type,
            exclude_user_ids=exclude_user_ids,
            commit=commit,
        )

    @staticmethod
    def send(user_id: str, title: str, message: str, link: str = None, type: str = 'info', commit: bool = True):
        """
        Sends a single notification to a specific user (Synchronous).

        Args:
            user_id (str): Recipient user UUID.
            title (str): Notification title.
            message (str): Notification content.
            link (str, optional): Destination URL.
            type (str): Category variant.
            commit (bool): Whether to commit the database session.

        Returns:
            Notification: The created notification object.
        """
        if not user_id:
            return

        notif = Notification(
            user_id=user_id,
            title=title,
            message=message,
            link=link,
            type=type
        )
        db.session.add(notif)
        if commit:
            db.session.commit()
        return notif

    @staticmethod
    def _normalize_user_map(users):
        """
        Normalizes various user inputs (objects or IDs) into a unique user ID map.

        Args:
            users (list): Mixed list of User objects or ID strings.

        Returns:
            dict: Map of user IDs to their respective objects/IDs.
        """
        user_map = {}
        for user in users or []:
            if not user:
                continue

            user_id = getattr(user, 'id', user)
            if user_id:
                user_map[str(user_id)] = user

        return user_map

    @staticmethod
    def notify_assignment_changes(
        previous_users: list,
        current_users: list,
        *,
        assigned_title: str,
        assigned_message: str,
        link: str = None,
        unassigned_title: str = None,
        unassigned_message: str = None,
        type: str = 'info',
        commit: bool = True,
    ):
        """
        Sends notifications for assignee changes (additions and removals).

        Args:
            previous_users (list): List of previous assignee objects or IDs.
            current_users (list): List of current assignee objects or IDs.
            assigned_title (str): Title for newly assigned users.
            assigned_message (str): Message for newly assigned users.
            link (str, optional): Destination URL.
            unassigned_title (str, optional): Title for removed users.
            unassigned_message (str, optional): Message for removed users.
            type (str): Notification variant.
            commit (bool): Commit transaction.

        Returns:
            dict: Counts for 'added' and 'removed' notifications.
        """
        previous_map = NotificationService._normalize_user_map(previous_users)
        current_map = NotificationService._normalize_user_map(current_users)

        added_user_ids = [user_id for user_id in current_map if user_id not in previous_map]
        removed_user_ids = [user_id for user_id in previous_map if user_id not in current_map]

        for user_id in added_user_ids:
            NotificationService.send(
                user_id,
                assigned_title,
                assigned_message,
                link=link,
                type=type,
                commit=False,
            )

        if unassigned_title and unassigned_message:
            for user_id in removed_user_ids:
                NotificationService.send(
                    user_id,
                    unassigned_title,
                    unassigned_message,
                    link=link,
                    type=type,
                    commit=False,
                )

        if commit and (added_user_ids or removed_user_ids):
            db.session.commit()

        return {'added': len(added_user_ids), 'removed': len(removed_user_ids)}

    @staticmethod
    async def send_async(user_id: str, title: str, message: str, link: str = None, type: str = 'info'):
        """
        Sends a notification asynchronously. Use this in async route handlers.

        Args:
            user_id (str): Recipient user UUID.
            title (str): Notification title.
            message (str): Notification body.
            link (str, optional): Destination URL.
            type (str): Category type.
        """
        from flask import current_app
        app = current_app._get_current_object()
        
        def _send():
            with app.app_context():
                NotificationService.send(user_id, title, message, link, type)

        await asyncio.to_thread(_send)

    @staticmethod
    def mark_as_read(notification_id: str, user_id: str):
        """
        Marks a specific notification as read.

        Args:
            notification_id (str): UUID of the notification.
            user_id (str): Owner user UUID for security verification.

        Returns:
            bool: True if successfully marked as read, False otherwise.
        """
        notif = db.session.get(Notification, notification_id)
        if notif and notif.user_id == user_id:
            notif.is_read = True
            db.session.commit()
            return True
        return False

    @staticmethod
    async def mark_as_read_async(notification_id: str, user_id: str):
        """
        Asynchronously marks a notification as read.

        Args:
            notification_id (str): UUID of the notification.
            user_id (str): UUID of the owner user.

        Returns:
            bool: True if success.
        """
        from flask import current_app
        app = current_app._get_current_object()
        
        def _mark():
            with app.app_context():
                return NotificationService.mark_as_read(notification_id, user_id)

        return await asyncio.to_thread(_mark)

    @staticmethod
    def get_unread_count(user_id: str):
        """
        Returns the count of unread notifications for a user.

        Args:
            user_id (str): User UUID.

        Returns:
            int: Unread notification count.
        """
        return Notification.query.filter_by(user_id=user_id, is_read=False).count()
