from minio import Minio
import os
from datetime import datetime
from io import BytesIO

# Configura cliente MinIO
minio_client = Minio(
    endpoint=os.getenv("MINIO_ENDPOINT", "minio:9000").replace("http://", ""),
    access_key=os.getenv("MINIO_ACCESS_KEY", "admin"),
    secret_key=os.getenv("MINIO_SECRET_KEY", "password"),
    secure=False
)

BUCKET = os.getenv("MINIO_BUCKET", "data")

# Cria bucket se não existir
if not minio_client.bucket_exists(BUCKET):
    minio_client.make_bucket(BUCKET)

def upload_image_to_minio(image_file, person_id):
    now = datetime.now().strftime("%Y%m%d-%H%M%S")
    filename = f"faces/{person_id}/{now}.jpg"

    image_file.seek(0)
    content = image_file.read()
    buffer = BytesIO(content)

    minio_client.put_object(
        bucket_name=BUCKET,
        object_name=filename,
        data=buffer,
        length=len(content),
        content_type="image/jpeg"
    )
    return filename
