from typing import Any, Dict

import dataiku
from backend.utils.logging_utils import get_logger
from backend.utils.user_utils import get_user_info

logger = get_logger(__name__)


def project_permissions(project_key: str) -> Dict[str, Any]:
    client = dataiku.api_client()
    project = client.get_project(project_key)
    permissions: Dict[str, Any] = project.get_permissions()
    return permissions


# not called anymore, but may be useful in the future
def user_has_access_to_project(user: str, project_key: str) -> bool:
    permissions = project_permissions(project_key)
    client = dataiku.api_client()
    user_groups = get_user_info(user).groups  # No need to be admin
    logger.debug(f"User [{user}] groups: {user_groups}")
    logger.debug(f"Project [{project_key}] permissions: {permissions}")
    if user == permissions.get("owner", ""):
        logger.debug("User is the admin to the project")
        return True
    elif any(
        group
        in {
            permission.get("group")
            for permission in permissions.get("permissions", [])
            if permission.get("readProjectContent", False)
        }
        for group in user_groups
    ) or any(client.get_group(group).get_definition().get("admin", False) for group in user_groups):
        logger.debug("User is part of the group that has access to the project")
        # check if user is part of the groups that have access to the project
        return True
    elif user in {
        permission.get("user")
        for permission in permissions.get("permissions", [])
        if permission.get("readProjectContent", False) or permission.get("admin", False)
    }:
        logger.debug("User is part of the users that have access to the project")
        return True
    else:
        logger.debug("User does not have access to the project")
        return False
