import face_recognition
import os
import numpy as np

def YuFase(Value, Database, tolerance=0.5):
    if not os.path.exists(Value):
        return "Aranan görsel bulunamadı"

    if not os.path.exists(Database):
        return "Veritabanı klasörü bulunamadı"

    image = face_recognition.load_image_file(Value)
    encodings = face_recognition.face_encodings(image)

    if len(encodings) == 0:
        return "Görselde yüz bulunamadı"

    target_encoding = encodings[0]

    best_match = None
    best_distance = 1.0
    found_name = None

    for root, dirs, files in os.walk(Database):
        for file in files:
            if file.lower().endswith((".png", ".jpg", ".jpeg")):
                path = os.path.join(root, file)

                try:
                    db_image = face_recognition.load_image_file(path)
                    db_encodings = face_recognition.face_encodings(db_image)

                    if len(db_encodings) == 0:
                        continue

                    db_encoding = db_encodings[0]
                    distance = face_recognition.face_distance(
                        [db_encoding],
                        target_encoding
                    )[0]

                    if distance < best_distance:
                        best_distance = distance
                        best_match = path
                        parent_folder = os.path.basename(os.path.dirname(path))

                        if parent_folder != os.path.basename(Database):
                            found_name = parent_folder

                except:
                    continue

    if best_distance < tolerance:
        if found_name:
            return {
                "durum": "Bulundu",
                "isim": found_name,
                "guven": float(1 - best_distance),
                "dosya": best_match
            }
        else:
            return {
                "durum": "Benzer bulundu",
                "guven": float(1 - best_distance),
                "dosya": best_match
            }

    return "Kişi bulunamadı"