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 are the project owner.
    """
    login = current_request_login() or ""

    is_admin = is_owner_or_admin(dataiku.default_project_key(), login)

    display_name = ""
    email = ""
    try:
        if login:
            ui = get_user_info(login)
            display_name = ui.display_name or ""
            email = ui.email or ""
    except Exception:
        # Leave display_name/email empty if user lookup fails
        logger.exception(f"Failed to get user info for login '{login}'")
        pass

    return jsonify(
        {
            "login": login,
            "displayName": display_name,
            "email": email,
            "isProjectAdmin": is_admin,
        }
    ), 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
