from __future__ import annotations

import dataiku
from flask import Blueprint, jsonify

from backend.utils.client_utils import current_request_login
from backend.utils.dss_utils import with_impersonation
from backend.utils.logger_utils import log_http_request
from backend.utils.logging_utils import get_logger
from backend.utils.permissions_utils import has_project_write_access
from backend.utils.user_utils import get_user_info
from backend.utils.utils import get_store

users_bp = Blueprint("users", __name__, url_prefix="/users")
logger = get_logger(__name__)


@with_impersonation
def has_dataset_read_access(project_key: str, dataset_name: str, login: str) -> bool:
    if not login:
        return False
    try:
        client = dataiku.api_client()
        permissions_check = client.new_permission_check()

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


@users_bp.route("/me", methods=["GET"])
@log_http_request
def me():
    """
    Returns the current user identity (login, displayName, email)
    and whether they have write access to the current project.
    """
    login = current_request_login() or ""
    project_key = dataiku.default_project_key()

    display_name = ""
    email = ""
    has_write_access = False

    try:
        if login:
            info = get_user_info(login).get_raw()
            display_name = info.get("displayName", "")
            email = info.get("email", "")

            logger.info(
                f"Retrieved user info for login '{login}': displayName='{display_name}', email='{email}', ui='{info}'"
            )

            has_write_access = has_project_write_access(project_key, login)

    except Exception:
        logger.exception(f"Failed to get user info or check permissions for login '{login}'")
        pass

    return (
        jsonify({"login": login, "displayName": display_name, "email": email, "hasWriteAccess": has_write_access}),
        200,
    )


@users_bp.route("/agent-owners", methods=["GET"])
@log_http_request
def agent_owners():
    """
    Returns owners of user agents only with their agent counts.
    """
    store = get_store()
    try:
        owners = store.list_user_agent_owners()
    except Exception:
        owners = []

    return jsonify({"owners": owners}), 200
