from __future__ import annotations

import dataiku
from flask import Blueprint, jsonify

from backend.utils.logger_utils import log_http_request
from backend.utils.logging_utils import get_logger
from backend.utils.project_utils import current_project_owner_login
from backend.utils.user_utils import get_user_info, is_owner_or_admin
from backend.utils.utils import current_request_login, get_store

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


@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}'"
            )

            # Check write permissions using impersonation
            with dataiku.WebappImpersonationContext() as context:
                client = dataiku.api_client()
                permissions_check = client.new_permission_check()

                # Check write permission on the project
                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}")
                if checks["items"] and checks["items"][0]["permitted"]:
                    has_write_access = True

    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
