from typing import Any

import dataiku
from backend.utils.dss_utils import with_impersonation
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


@with_impersonation
def has_project_write_access(project_key: str, login: str) -> bool:
    if not login:
        return False

    try:
        client = dataiku.api_client()
        permissions_check = client.new_permission_check()

        permissions_check.with_item("PROJECT", project_key, project_key)
        item = permissions_check.request["items"][0]
        item["mode"] = "WRITE"
        checks = permissions_check.execute_raw()
        logger.info(f"Permission checks for user '{login}': {checks}")
        return bool(checks.get("items") and checks["items"][0].get("permitted"))
    except Exception:
        logger.exception(f"Failed to check write permissions for login '{login}'")
        return False


# 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
