"""Shared utilities for icv-search services."""

from __future__ import annotations

from icv_search.models import SearchIndex


def resolve_index(name_or_index: str | SearchIndex, tenant_id: str = "") -> SearchIndex:
    """Resolve an index name or SearchIndex instance to a SearchIndex.

    Args:
        name_or_index: Index name string or SearchIndex instance.
        tenant_id: Tenant identifier (only needed when passing a name).

    Returns:
        The resolved SearchIndex instance.

    Raises:
        SearchIndex.DoesNotExist: If no matching index is found.
    """
    if isinstance(name_or_index, SearchIndex):
        return name_or_index
    return SearchIndex.objects.get(name=name_or_index, tenant_id=tenant_id)


def resolve_tenant_id(explicit_tenant_id: str) -> str:
    """Return the effective tenant identifier for a service call.

    Resolution order:

    1. ``explicit_tenant_id`` — if non-empty, returned as-is (explicit wins).
    2. The request-scoped tenant set by
       :class:`~icv_search.middleware.ICVSearchTenantMiddleware` via
       :func:`~icv_search.middleware.get_current_tenant_id`.
    3. An empty string (single-tenant / no-tenant mode).

    Args:
        explicit_tenant_id: The tenant identifier supplied directly by the caller.

    Returns:
        The resolved tenant identifier string (may be empty).
    """
    if explicit_tenant_id:
        return explicit_tenant_id
    from icv_search.middleware import get_current_tenant_id

    return get_current_tenant_id()
