"""Face Search resource — 1:N face duplicate detection."""

from __future__ import annotations

from dataclasses import asdict
from typing import Any, Dict, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from ..http_client import AsyncHttpClient, HttpClient

__all__ = ["FaceSearch", "AsyncFaceSearch"]


class FaceSearch:
    """1:N face duplicate detection (synchronous).

    Example::

        result = verilock.face_search.search(
            FaceSearchParams(session_id="sess_123", threshold=90)
        )
        if result["duplicate_found"]:
            print(f"Duplicate: {result['highest_similarity']}% similarity")
    """

    def __init__(self, http: HttpClient) -> None:
        self._http = http

    def search(
        self,
        params: Any,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Search for duplicate faces against all verified sessions.

        Requires the ``face_search`` license feature.

        Args:
            params: A :class:`~verilock.types.face_search.FaceSearchParams` or dict.

        Returns:
            Face search result with matches and similarity scores.
        """
        body = asdict(params) if hasattr(params, "__dataclass_fields__") else params
        body = {k: v for k, v in body.items() if v is not None}
        return self._http.post("/v1/face-search", body, idempotency_key=idempotency_key)

    def retrieve(
        self,
        search_id: str,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Retrieve a previous face search result.

        Args:
            search_id: The face search ID.

        Returns:
            Full face search result with matches.
        """
        return self._http.get(
            f"/v1/face-search/{search_id}", idempotency_key=idempotency_key
        )


class AsyncFaceSearch:
    """1:N face duplicate detection (asynchronous)."""

    def __init__(self, http: AsyncHttpClient) -> None:
        self._http = http

    async def search(
        self,
        params: Any,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Search for duplicate faces against all verified sessions."""
        body = asdict(params) if hasattr(params, "__dataclass_fields__") else params
        body = {k: v for k, v in body.items() if v is not None}
        return await self._http.post(
            "/v1/face-search", body, idempotency_key=idempotency_key
        )

    async def retrieve(
        self,
        search_id: str,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Retrieve a previous face search result."""
        return await self._http.get(
            f"/v1/face-search/{search_id}", idempotency_key=idempotency_key
        )
