from apps.core.repositories import UserRepository
from apps.userprofile.repositories import UserProfileRepository


class ProfileServices:

    @staticmethod
    def capitalize_first_letters(value: str) -> str:
        return _capitalize_first_letters(value)

    @staticmethod
    def resolve_display_name(
        *,
        user=None,
        profile=None,
        user_id=None,
        profile_id=None,
    ) -> str:
        """
        Resolution order:
        1. Explicit profile
        2. Profile via profile_id
        3. Profile via user / user_id
        4. Username
        5. "Unknown"
        """

        if user_id and not user:
            user = UserRepository.get_by_id(user_id=user_id)

        if profile_id and not profile:
            profile = UserProfileRepository.get_by_id(profile_id=profile_id)

        if not profile and user:
            profile = getattr(user, "profile", None)

        if profile:
            full_name = _extract_full_name(profile)
            if full_name:
                return _capitalize_first_letters(full_name)

        if user and user.username:
            return _capitalize_first_letters(user.username)

        return "Unknown"

    @staticmethod
    def display_name_for_company(user, company):
        status = user.status_for_company(company)
        name = ProfileServices.resolve_display_name(user=user)
        return f"{name}{status['suffix']}"

def _extract_full_name(profile) -> str:
    first = profile.first_name or ""
    last = profile.last_name or ""
    return f"{first} {last}".strip()

def _capitalize_first_letters(value: str) -> str:
    """
    Capitalizes the first letter of each space-separated part.
    Safer than .title()
    """
    return " ".join(
        word[:1].upper() + word[1:].lower()
        if word else ""
        for word in value.split(" ")
    )
