"""AWS Rekognition client + face-recognition helpers for HR attendance."""

from functools import lru_cache

import boto3
from botocore.exceptions import ClientError
from django.conf import settings


@lru_cache(maxsize=1)
def get_client():
    return boto3.client(
        'rekognition',
        aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
        aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
        region_name=settings.AWS_REGION,
    )


def ensure_collection(collection_id: str | None = None) -> str:
    collection_id = collection_id or settings.REKOGNITION_COLLECTION_ID
    client = get_client()
    try:
        client.create_collection(CollectionId=collection_id)
    except ClientError as exc:
        if exc.response['Error']['Code'] != 'ResourceAlreadyExistsException':
            raise
    return collection_id


def index_face(image_bytes: bytes, external_image_id: str, collection_id: str | None = None) -> dict:
    """Enroll a face. external_image_id should be the employee's stable id (e.g. user uuid)."""
    return get_client().index_faces(
        CollectionId=collection_id or settings.REKOGNITION_COLLECTION_ID,
        Image={'Bytes': image_bytes},
        ExternalImageId=external_image_id,
        DetectionAttributes=['DEFAULT'],
        MaxFaces=1,
        QualityFilter='AUTO',
    )


def search_face(image_bytes: bytes, collection_id: str | None = None) -> dict | None:
    """Match a face against the collection. Returns top match or None."""
    response = get_client().search_faces_by_image(
        CollectionId=collection_id or settings.REKOGNITION_COLLECTION_ID,
        Image={'Bytes': image_bytes},
        FaceMatchThreshold=settings.REKOGNITION_FACE_MATCH_THRESHOLD,
        MaxFaces=1,
    )
    matches = response.get('FaceMatches') or []
    return matches[0] if matches else None
