from typing import List

import dataiku
from backend.utils.logging_utils import get_logger

logger = get_logger(__name__)


# user info properties:
# login(self)
# display_name(self):
# groups(self):
# email(self):
# enabled(self):
def get_user_info(user: str):
    client = dataiku.api_client()
    return client.get_user(user).get_info()


def get_agent_context(user: str, conv_id: str):
    from backend.utils.dss_utils import compare_versions
    from flask import request

    client = dataiku.api_client()
    user_info = client.get_user(user).get_info().get_raw()
    cont = {
        "callerSecurityTokens": format_security_tokens(user_info),
        "dku_user_email": user_info.get("email", ""),
        "dku_user_login": user_info.get("login", ""),
        "dku_user_display_name": user_info.get("displayName", ""),
        "conversationId": conv_id,
        "dkuOnBehalfOf": user_info.get("login", ""),
    }
    # Only send callerTicket for dss >= 14.3.2 to make sure they are redacted properly
    dss_version = client.get_instance_info().raw.get("dssVersion", "0.0.0")
    if (compare_versions(dss_version, "14.3.2")) >= 0:
        cont["dkuCallerTicket"] = client.get_ticket_from_browser_headers(headers_dict=dict(request.headers))
    return cont

def format_security_tokens(user_info) -> List[str]:
    user_data = []
    user_data.append(f"dss_user_login:{user_info.get('login', '')}")
    user_data.append(f"dss_user_emailaddress:{user_info.get('email', '')}")
    return user_info.get("groups", []) + [f"dss_group:{group}" for group in user_info.get("groups", [])] + user_data


def is_owner_or_admin(project_key: str, user_login: str) -> bool:
    client = dataiku.api_client()
    project = client.get_project(project_key)

    perms = project.get_permissions()
    owner_login = perms.get("owner") or ""
    is_owner = bool(user_login and owner_login and user_login == owner_login)

    uinfo = client.get_user(user_login).get_info()
    user_groups = set(uinfo.groups)

    entries = perms.get("permissions", [])

    direct_admin = any(e.get("user") == user_login and e.get("admin", False) for e in entries)

    group_admin = any(e.get("group") in user_groups and e.get("admin", False) for e in entries)

    return is_owner or direct_admin or group_admin
