from PIL import Image

def crop_gif(input_gif, output_gif, remove_top=0, remove_bottom=0, remove_left=0, remove_right=0, use_percentage=False):
    """
    Recorta píxeles o porcentajes de cualquier dirección de todos los frames de un GIF.
    
    Args:
        input_gif: Ruta del GIF de entrada
        output_gif: Ruta del GIF de salida
        remove_top: Píxeles o porcentaje a remover desde arriba
        remove_bottom: Píxeles o porcentaje a remover desde abajo
        remove_left: Píxeles o porcentaje a remover desde la izquierda
        remove_right: Píxeles o porcentaje a remover desde la derecha
        use_percentage: Si es True, los valores son porcentajes (0-100). Si es False, son píxeles
    """
    
    # Abrir el GIF
    gif = Image.open(input_gif)
    
    # Obtener información del GIF
    original_width, original_height = gif.size
    
    # Convertir porcentajes a píxeles si es necesario
    if use_percentage:
        remove_top_px = int(original_height * remove_top / 100)
        remove_bottom_px = int(original_height * remove_bottom / 100)
        remove_left_px = int(original_width * remove_left / 100)
        remove_right_px = int(original_width * remove_right / 100)
        
        print("=" * 50)
        print("CONVERSIÓN DE PORCENTAJES A PÍXELES:")
        print(f"  Arriba: {remove_top}% = {remove_top_px}px")
        print(f"  Abajo: {remove_bottom}% = {remove_bottom_px}px")
        print(f"  Izquierda: {remove_left}% = {remove_left_px}px")
        print(f"  Derecha: {remove_right}% = {remove_right_px}px")
    else:
        remove_top_px = remove_top
        remove_bottom_px = remove_bottom
        remove_left_px = remove_left
        remove_right_px = remove_right
    
    # Calcular nuevas dimensiones
    new_width = original_width - remove_left_px - remove_right_px
    new_height = original_height - remove_top_px - remove_bottom_px
    
    print("=" * 50)
    print(f"GIF original: {original_width}x{original_height}")
    print(f"Removiendo píxeles:")
    print(f"  - Arriba: {remove_top_px}px")
    print(f"  - Abajo: {remove_bottom_px}px")
    print(f"  - Izquierda: {remove_left_px}px")
    print(f"  - Derecha: {remove_right_px}px")
    print(f"GIF resultante: {new_width}x{new_height}")
    print("=" * 50)
    
    # Validar dimensiones
    if new_width <= 0 or new_height <= 0:
        print("ERROR: Las dimensiones resultantes son inválidas")
        print(f"Ancho resultante: {new_width}")
        print(f"Alto resultante: {new_height}")
        return
    
    # Lista para almacenar los frames procesados
    frames = []
    
    # Extraer información de duración
    try:
        duration = gif.info.get('duration', 100)
    except:
        duration = 100
    
    # Procesar cada frame
    frame_count = 0
    try:
        while True:
            # Copiar el frame actual
            frame = gif.copy()
            
            # Recortar el frame
            cropped_frame = frame.crop((
                remove_left_px,                    # x inicial
                remove_top_px,                     # y inicial
                original_width - remove_right_px,  # x final
                original_height - remove_bottom_px # y final
            ))
            
            # Agregar el frame recortado a la lista
            frames.append(cropped_frame)
            
            frame_count += 1
            if frame_count % 10 == 0:
                print(f"Procesados {frame_count} frames...")
            
            # Intentar ir al siguiente frame
            gif.seek(gif.tell() + 1)
            
    except EOFError:
        # Se llegó al final del GIF
        pass
    
    print(f"Total de frames procesados: {frame_count}")
    
    # Guardar el nuevo GIF con todos los frames recortados
    if frames:
        print(f"Guardando GIF recortado en: {output_gif}")
        frames[0].save(
            output_gif,
            save_all=True,
            append_images=frames[1:],
            duration=duration,
            loop=0,
            disposal=2,
            optimize=True
        )
        print("¡GIF recortado exitosamente!")
    else:
        print("ERROR: No se pudieron procesar frames")


def crop_gif_simple(input_gif, output_gif, amount_to_remove, direction='bottom', use_percentage=False):
    """
    Versión simple: recorta píxeles o porcentaje desde una sola dirección.
    
    Args:
        input_gif: Ruta del GIF de entrada
        output_gif: Ruta del GIF de salida
        amount_to_remove: Cantidad de píxeles o porcentaje a remover
        direction: 'top', 'bottom', 'left', 'right'
        use_percentage: Si es True, amount_to_remove es un porcentaje (0-100)
    """
    
    directions = {
        'top': {'remove_top': amount_to_remove},
        'bottom': {'remove_bottom': amount_to_remove},
        'left': {'remove_left': amount_to_remove},
        'right': {'remove_right': amount_to_remove}
    }
    
    if direction not in directions:
        print(f"ERROR: Dirección '{direction}' no válida. Usa: 'top', 'bottom', 'left', 'right'")
        return
    
    crop_gif(input_gif, output_gif, use_percentage=use_percentage, **directions[direction])


def get_gif_info(input_gif):
    """
    Muestra información sobre el GIF.
    
    Args:
        input_gif: Ruta del GIF
    """
    gif = Image.open(input_gif)
    width, height = gif.size
    
    # Contar frames
    frame_count = 0
    try:
        while True:
            frame_count += 1
            gif.seek(gif.tell() + 1)
    except EOFError:
        pass
    
    duration = gif.info.get('duration', 'Desconocido')
    
    print("=" * 50)
    print("INFORMACIÓN DEL GIF")
    print("=" * 50)
    print(f"Dimensiones: {width}x{height} píxeles")
    print(f"Total de frames: {frame_count}")
    print(f"Duración por frame: {duration}ms")
    print(f"Modo de color: {gif.mode}")
    print("=" * 50)


# Ejemplos de uso
if __name__ == "__main__":
    input_file = "astrofinal.gif"
    
    # Ver información del GIF primero (opcional)
    get_gif_info(input_file)
    

    
    # Ejemplo 3: Recortar 5% de todos los lados (marco)
    crop_gif(
        input_file, 
        "salida_marco.gif",
        remove_top=0,
        remove_bottom=0,
        remove_left=17,
        remove_right=15,
        use_percentage=True
    )
    
    # Ejemplo 4: Versión simple - 20% de abajo

    
    # ===== USANDO PÍXELES =====
    
    # Ejemplo 5: Recortar 100 píxeles de abajo
    # crop_gif(input_file, "salida.gif", remove_bottom=100, use_percentage=False)
    
    # Ejemplo 6: Recortar píxeles de múltiples lados
    # crop_gif(
    #     input_file, 
    #     "salida.gif",
    #     remove_top=50,
    #     remove_bottom=100,
    #     remove_left=30,
    #     remove_right=30,
    #     use_percentage=False  # o simplemente omitir, False es el valor por defecto
    # )