# -*- coding: utf-8 -*-
"""Face 检测 HTTP 客户端。"""
from typing import Union

import requests

from gshield_pic_sdk._image import to_bytes
from gshield_pic_sdk.exceptions import GshieldConnectionError

ImageInput = Union[str, bytes, "np.ndarray"]


class FaceClient:
    """人脸检测服务客户端，调用 face 服务的 POST /detect。"""

    def __init__(self, face_base_url: str, timeout: int = 30):
        self.base_url = face_base_url.rstrip("/")
        self.timeout = timeout

    def detect(self, image: ImageInput) -> dict:
        """
        上传图片做人脸检测与识别。
        :param image: 图片路径(str)、bytes 或 ndarray
        :return: {"faces": [...], "count": N}
        """
        data = to_bytes(image)
        url = f"{self.base_url}/detect"
        try:
            r = requests.post(
                url,
                files={"image": ("image.jpg", data, "image/jpeg")},
                timeout=self.timeout,
            )
        except requests.RequestException as e:
            raise GshieldConnectionError(f"face detect request failed: {e}") from e
        if r.status_code >= 400:
            raise GshieldConnectionError(
                f"face detect returned {r.status_code}: {r.text}"
            )
        out = r.json()
        if "faces" not in out or "count" not in out:
            raise GshieldConnectionError(f"unexpected face response: {out}")
        return out
