import io
import logging
import os.path

import numpy as np
# import boto3
from minio import Minio
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip

from app.core.config import *
from app.service.utils.new_oss_client import oss_upload_image

# minio 配置
MINIO_URL = "www.minio-api.aida.com.hk"
MINIO_ACCESS = 'vXKFLSJkYeEq2DrSZvkB'
MINIO_SECRET = 'uKTZT3x7C43WvPN9QTc99DiRkwddWZrG9Uh3JVlR'
MINIO_SECURE = True
minio_client = Minio(MINIO_URL, access_key=MINIO_ACCESS, secret_key=MINIO_SECRET, secure=MINIO_SECURE)


def upload_first_image(image, user_id, category, file_name):
    try:
        image_data = io.BytesIO()
        image.save(image_data, format='PNG')
        image_data.seek(0)
        image_bytes = image_data.read()
        object_name = f'{user_id}/{category}/{file_name}'
        req = oss_upload_image(oss_client=minio_client, bucket=GI_MINIO_BUCKET, object_name=object_name, image_bytes=image_bytes)
        image_url = f"aida-users/{object_name}"
        return image_url
    except Exception as e:
        logging.warning(f"upload_png_mask runtime exception : {e}")


def upload_gif(gif_buffer, user_id, category, file_name):
    try:
        object_name = f'{user_id}/{category}/{file_name}'
        req = minio_client.put_object(
            "aida-users",
            object_name,
            gif_buffer,
            length=gif_buffer.getbuffer().nbytes,
            content_type="image/gif"
        )
        return f"aida-users/{object_name}"
    except Exception as e:
        logging.warning(f"upload_gif runtime exception : {e}")


def upload_video(frames, user_id, category, file_name):
    try:
        save_path = ndarray_to_video(frames, file_name)
        object_name = f'{user_id}/{category}/{file_name}'
        minio_client.fput_object(
            "aida-users",
            object_name,
            save_path,
            content_type="video/mp4"  # 指定MIME类型确保可在线播放[9](@ref)
        )
        return f"aida-users/{object_name}"
    except Exception as e:
        logging.warning(f"upload_video runtime exception : {e}")


def ndarray_to_video(images, output_path, frame_size=(512, 768), fps=9):
    save_path = os.path.join(POSE_TRANSFORM_VIDEO_PATH, output_path)
    clip = ImageSequenceClip([frame for frame in images], fps=fps)
    clip.write_videofile(save_path, codec='libx264')

    return save_path


if __name__ == '__main__':
    images = np.random.randint(0, 256, size=(4, 768, 512, 3), dtype=np.uint8)
    print(upload_video(images, user_id=89, category='pose_transform_video', file_name="1123123.mp4"))
