import imageio
from PIL import Image, ImageEnhance
import numpy as np
import os

def create_3d_flip_imageio(front_path, back_path, output_path, frames=72, fps=30):
    """
    Creates a 3D flipping animation GIF using imageio, handling palettes and transparency.

    Parameters:
    - front_path (str): File path to the front image (PNG with transparency).
    - back_path (str): File path to the back image (PNG with transparency).
    - output_path (str): File path where the output GIF will be saved.
    - frames (int): Total number of frames in the GIF.
    - fps (int): Frames per second for the GIF animation.
    """
    # Load both front and back images with RGBA channels to preserve transparency
    front_logo = Image.open(front_path).convert('RGBA')
    back_logo = Image.open(back_path).convert('RGBA')

    # Ensure both images are the same size
    if front_logo.size != back_logo.size:
        raise ValueError("Front and back images must have the same dimensions.")

    width, height = front_logo.size

    # Define canvas size with padding for rotation
    canvas_size = (int(width * 1.3), int(height * 1.3))
    frames_list = []

    for i in range(frames):
        # Calculate rotation angle for this frame (0 to 360 degrees)
        angle = (i / frames) * 360

        # Create a new transparent canvas
        canvas = Image.new('RGBA', canvas_size, (0, 0, 0, 0))

        # Determine which logo to use based on rotation angle
        if 90 <= angle < 270:
            current_logo = back_logo
            # Adjust angle for back side to maintain correct rotation direction
            display_angle = angle - 180
        else:
            current_logo = front_logo
            display_angle = angle

        # Calculate scaling factor for perspective effect (simulating 3D rotation)
        scale_factor = 0.7 + 0.3 * abs(np.cos(np.radians(angle)))

        # Calculate new dimensions with perspective scaling
        new_width = int(width * scale_factor)
        new_height = int(height * scale_factor)

        # Resize the current logo with high-quality resampling
        frame_logo = current_logo.resize((new_width, new_height), Image.LANCZOS)

        # Rotate the logo around its center
        frame_logo = frame_logo.rotate(display_angle, expand=True, resample=Image.BICUBIC)

        # Calculate position to center the rotated logo on the canvas
        paste_x = (canvas_size[0] - frame_logo.width) // 2
        paste_y = (canvas_size[1] - frame_logo.height) // 2

        # Add subtle brightness variation based on rotation to simulate lighting
        enhancer = ImageEnhance.Brightness(frame_logo)
        brightness_factor = 0.8 + 0.2 * abs(np.cos(np.radians(angle)))
        frame_logo = enhancer.enhance(brightness_factor)

        # Paste the logo onto the canvas using its alpha channel as mask for transparency
        canvas.paste(frame_logo, (paste_x, paste_y), frame_logo)

        # Convert the PIL Image to a NumPy array for imageio
        frame_array = np.array(canvas)
        frames_list.append(frame_array)

    # Create output directory if it doesn't exist
    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    # Calculate duration per frame in seconds
    duration_sec = 1 / fps

    # Save the frames as a GIF using imageio
    try:
        imageio.mimsave(
            output_path,
            frames_list,
            format='GIF',
            duration=duration_sec,
            loop=0,
            palettesize=256,
            subrectangles=True  # Allows for optimization by using subrectangles
        )
        print(f"3D flipping animation saved to {output_path}")
    except Exception as e:
        print(f"Failed to save GIF with imageio: {e}")

if __name__ == "__main__":
    # Define file paths
    front_path = "/root/auto/img/transparent.png"        # Path to the front image (PNG with transparency)
    back_path = "/root/auto/img/rev_logo.png"            # Path to the back image (PNG with transparency)
    output_path = "/root/auto/output/spin_effect.gif"    # Desired output path for the GIF

    # Create the 3D flipping animation GIF using imageio
    create_3d_flip_imageio(front_path, back_path, output_path) A basic rotation of a vector in 3-dimensions is a rotation around one of the coordinate axes. We can rotate a vector counterclockwise through an angle θ around the x–axis, the y–axis, or the z–axis. To get a counterclockwise view, imagine looking at an axis straight on toward the origin.