import os
from minio import Minio
from minio.error import S3Error

from constants import MINIO_SERVER, MINIO_DATA_LABELED, MINIO_MODEL_TRAINED, MODEL_CHECKPOINT
from logger import logger

minio_client = Minio(
    endpoint=MINIO_SERVER,
    access_key=os.getenv("MINIO_ROOT_USER"),
    secret_key=os.getenv("MINIO_ROOT_PASSWORD"),
    secure=False
)
bucket_names = [MINIO_DATA_LABELED, MINIO_MODEL_TRAINED]

def download_latest_model():
    # List objects in the bucket
    objects = minio_client.list_objects(MINIO_MODEL_TRAINED)
    latest_obj = None
    latest_time = None
    
    for obj in objects:
        if "last" in obj.object_name:
            if latest_time is None or obj.last_modified > latest_time:
                latest_time = obj.last_modified
                latest_obj = obj

    if latest_obj is not None:
        try:
            minio_client.fget_object(MINIO_MODEL_TRAINED, latest_obj.object_name, MODEL_CHECKPOINT)
        except S3Error as exc:
            logger.error(f"Error occurred: {exc}")
        return latest_obj.object_name
    else:
        raise Exception("No *last* models found in the bucket")