#!/usr/bin/env python3
"""
Script to resize PNG asset files to 18x18 pixels and center them on a 20x20 canvas.
Saves the result back to the same file.
"""

import os
import glob
from PIL import Image, ImageOps
import argparse

def resize_and_center_image(image_path, target_size=(18, 18), canvas_size=(20, 20)):
    """
    Resize an image to target_size and center it on a canvas of canvas_size.
    
    Args:
        image_path (str): Path to the image file
        target_size (tuple): Size to resize the image to (width, height)
        canvas_size (tuple): Size of the final canvas (width, height)
    """
    try:
        # Open the image
        with Image.open(image_path) as img:
            # Convert to RGBA to handle transparency
            img = img.convert("RGBA")
            
            # Resize the image to target size using high-quality resampling
            resized_img = img.resize(target_size, Image.Resampling.LANCZOS)
            
            # Create a new transparent canvas
            canvas = Image.new("RGBA", canvas_size, (0, 0, 0, 0))
            
            # Calculate position to center the resized image
            x_offset = (canvas_size[0] - target_size[0]) // 2
            y_offset = (canvas_size[1] - target_size[1]) // 2
            
            # Paste the resized image onto the canvas
            canvas.paste(resized_img, (x_offset, y_offset), resized_img)
            
            # Save back to the same file
            canvas.save(image_path, "PNG", optimize=True)
            
            print(f"✓ Processed: {os.path.basename(image_path)}")
            
    except Exception as e:
        print(f"✗ Error processing {image_path}: {str(e)}")

def process_directory(directory_path, file_pattern="*.png"):
    """
    Process all PNG files in a directory.
    
    Args:
        directory_path (str): Path to the directory containing PNG files
        file_pattern (str): Pattern to match files (default: "*.png")
    """
    if not os.path.exists(directory_path):
        print(f"Error: Directory '{directory_path}' does not exist.")
        return
    
    # Find all PNG files matching the pattern
    search_pattern = os.path.join(directory_path, file_pattern)
    png_files = glob.glob(search_pattern)
    
    if not png_files:
        print(f"No PNG files found in '{directory_path}' matching pattern '{file_pattern}'")
        return
    
    print(f"Found {len(png_files)} PNG files to process...")
    
    # Process each file
    for png_file in png_files:
        resize_and_center_image(png_file)
    
    print(f"\nCompleted processing {len(png_files)} files.")

def process_single_file(file_path):
    """
    Process a single PNG file.
    
    Args:
        file_path (str): Path to the PNG file
    """
    if not os.path.exists(file_path):
        print(f"Error: File '{file_path}' does not exist.")
        return
    
    if not file_path.lower().endswith('.png'):
        print(f"Error: File '{file_path}' is not a PNG file.")
        return
    
    print(f"Processing single file: {os.path.basename(file_path)}")
    resize_and_center_image(file_path)
    print("Processing complete.")

def main():
    parser = argparse.ArgumentParser(description="Resize PNG assets to 18x18px and center on 20x20px canvas")
    parser.add_argument("path", help="Path to PNG file or directory containing PNG files")
    parser.add_argument("--pattern", default="*.png", help="File pattern to match (default: *.png)")
    
    args = parser.parse_args()
    
    if os.path.isfile(args.path):
        process_single_file(args.path)
    elif os.path.isdir(args.path):
        process_directory(args.path, args.pattern)
    else:
        print(f"Error: '{args.path}' is not a valid file or directory.")

if __name__ == "__main__":
    # If run without arguments, process the assets/Rat directory by default
    import sys
    if len(sys.argv) == 1:
        # Default to processing the assets/Rat directory
        script_dir = os.path.dirname(os.path.abspath(__file__))
        assets_dir = os.path.join(script_dir, "assets", "Rat")
        if os.path.exists(assets_dir):
            print("No arguments provided. Processing assets/Rat directory by default...")
            process_directory(assets_dir)
        else:
            print("assets/Rat directory not found. Please provide a path as argument.")
            print("Usage: python resize_assets.py <path_to_file_or_directory>")
    else:
        main()
