"""
Image Resizer

Resize images by %.

Created by Christopher (Egrigor86)
"""
__version__ = "0.1.0"

from PIL import Image
import sys
import os

def resize_image(input_path, output_path, scale_factor):
    """
    Resize an image by a scale factor.
    Example: scale_factor=0.5 makes the image half the width and height.
    """
    try:
        img = Image.open(input_path)

        # Calculate new size
        new_width = int(img.width * scale_factor)
        new_height = int(img.height * scale_factor)
        new_size = (new_width, new_height)

        # Resize with high-quality filter
        resized_img = img.resize(new_size, Image.LANCZOS)

        # Save resized image (keep same format if possible)
        resized_img.save(output_path, format=img.format)
        print(f"✅ Resized {input_path} → {output_path} ({new_size})")

    except Exception as e:
        print(f"❌ Error resizing {input_path}: {e}")

def process_folder(input_folder, output_folder, scale_factor):
    """
    Resize all images in a folder by scale_factor.
    """
    os.makedirs(output_folder, exist_ok=True)
    supported_ext = (".png", ".jpg", ".jpeg", ".webp")

    for filename in os.listdir(input_folder):
        if filename.lower().endswith(supported_ext):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)
            resize_image(input_path, output_path, scale_factor)

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage:")
        print("  Single file: python resize.py input.png output.png 0.5")
        print("  Whole folder: python resize.py input_folder output_folder 0.5")
        sys.exit(1)

    input_path = sys.argv[1]
    output_path = sys.argv[2]
    scale_factor = float(sys.argv[3])

    if os.path.isdir(input_path):
        # Process entire folder
        process_folder(input_path, output_path, scale_factor)
    elif os.path.isfile(input_path):
        # Process single file
        resize_image(input_path, output_path, scale_factor)
    else:
        print(f"Error: {input_path} not found.")
