"""Biometric resource — face authentication."""

from __future__ import annotations

import json
from typing import Any, Dict, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from ..http_client import AsyncHttpClient, HttpClient

__all__ = ["Biometric", "AsyncBiometric"]


class Biometric:
    """Biometric face authentication (synchronous).

    Example::

        auth = verilock.biometric.authenticate(
            BiometricAuthParams(
                session_id="sess_123",
                file=open("selfie.jpg", "rb").read(),
                threshold=85,
            )
        )
        # Poll for result
        result = verilock.biometric.retrieve(auth["id"])
    """

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

    def authenticate(
        self,
        params: Any,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Authenticate a user via biometric face matching against an approved session.

        Args:
            params: A :class:`~verilock.types.biometric.BiometricAuthParams` instance.

        Returns:
            Response with ``id``, ``status``, and ``message``.
        """
        fields: Dict[str, str] = {"session_id": params.session_id}
        if params.threshold is not None:
            fields["threshold"] = str(params.threshold)
        if params.device_info is not None:
            fields["device_info"] = json.dumps(params.device_info)

        return self._http.upload(
            "/v1/auth/biometric",
            params.file,
            params.filename or "selfie.jpg",
            fields,
            idempotency_key=idempotency_key,
        )

    def retrieve(
        self,
        auth_id: str,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Retrieve the result of a biometric authentication.

        Args:
            auth_id: The biometric authentication ID.

        Returns:
            Full biometric result with similarity scores and liveness data.
        """
        return self._http.get(
            f"/v1/auth/biometric/{auth_id}", idempotency_key=idempotency_key
        )


class AsyncBiometric:
    """Biometric face authentication (asynchronous)."""

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

    async def authenticate(
        self,
        params: Any,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Authenticate a user via biometric face matching against an approved session."""
        fields: Dict[str, str] = {"session_id": params.session_id}
        if params.threshold is not None:
            fields["threshold"] = str(params.threshold)
        if params.device_info is not None:
            fields["device_info"] = json.dumps(params.device_info)

        return await self._http.upload(
            "/v1/auth/biometric",
            params.file,
            params.filename or "selfie.jpg",
            fields,
            idempotency_key=idempotency_key,
        )

    async def retrieve(
        self,
        auth_id: str,
        *,
        idempotency_key: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Retrieve the result of a biometric authentication."""
        return await self._http.get(
            f"/v1/auth/biometric/{auth_id}", idempotency_key=idempotency_key
        )
