import os
import logging
import numpy as np
from PIL import Image
from deepface import DeepFace


# Configura logger
logging.basicConfig(
    level=logging.DEBUG if os.getenv("DEBUG", "True").lower() == "true" else logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)
threshold = float(os.getenv("THRESHOLD", 0.85))

def pil_to_numpy_rgb(image_file):
    """Converte qualquer imagem em numpy RGB"""
    image_file.seek(0)
    pil_image = Image.open(image_file).convert("RGB")
    return np.array(pil_image)

def compare_faces_service(image1_file, image2_file):
    """
    Compara duas imagens usando o modelo DeepFace Dlib.
    Retorna similaridade, match e tempo.
    """
    logger.info("📷 Iniciando comparação facial com DeepFace Dlib...")

    try:
        img1 = pil_to_numpy_rgb(image1_file)
        img2 = pil_to_numpy_rgb(image2_file)

        result = DeepFace.verify(
            img1,
            img2,
            model_name="Dlib",
            enforce_detection=False
        )

        similarity_score = 1 - result["distance"]
        is_same_person = result["verified"]

        logger.info(f"🔍 Match: {is_same_person} | Score: {similarity_score:.4f}")

        return {
            "match": bool(is_same_person),
            "similarity_score": round(float(similarity_score), 4),
            "threshold_used": threshold
        }

    except Exception as e:
        logger.exception("❌ Erro na comparação facial")
        raise ValueError(f"Erro na verificação: {str(e)}")
