import os
import sys
from PIL import Image

# --- Configuration ---
SCALE_FACTOR = 2  # Divisor: Images will be divided by this number (e.g., 2 means half size)
ALLOWED_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.bmp']
# ---------------------

def downscale_image_nearest_neighbor(input_path, divisor):
    """Downscales a single image by the given integer divisor using Nearest Neighbor and overwrites the original file."""
    try:
        img = Image.open(input_path)
        original_width, original_height = img.size
        
        # Calculate new dimensions
        new_width = original_width // divisor
        new_height = original_height // divisor

        if new_width < 1 or new_height < 1:
            return False, f"Skipped: Resulting size ({new_width}x{new_height}) is too small."
        
        if original_width == new_width and original_height == new_height:
             return False, "Skipped: Image is already at the target size or cannot be cleanly divided."

        # Downscale using Nearest Neighbor (Image.NEAREST) to prevent blurring
        downscaled_img = img.resize((new_width, new_height), Image.NEAREST)
        
        # Save the downscaled image, OVERWRITING THE ORIGINAL FILE
        downscaled_img.save(input_path)
        
        return True, f"OVERWRITTEN: Scaled from {original_width}x{original_height} to {new_width}x{new_height}"

    except Image.UnidentifiedImageError:
        return False, "Error: Could not identify image format."
    except Exception as e:
        return False, f"An unexpected error occurred: {e}"


def batch_downscale_interactive(divisor):
    """Interactively finds and downscales images in subdirectories, overwriting originals."""
    
    # --- SAFETY CHECK ---
    print("\n!!! WARNING: THIS SCRIPT WILL OVERWRITE YOUR ORIGINAL FILES !!!")
    input("Press Enter to continue or Ctrl+C to stop and make a backup...")
    # --------------------
    
    start_directory = os.getcwd()
    total_processed_count = 0
    
    # os.walk traverses the current directory and all subdirectories
    for root, dirs, files in os.walk(start_directory):
        
        # Skip the starting directory—it must always be processed if we start the script.
        # We only prompt for subdirectories (where root != start_directory)
        if root != start_directory:
            
            # --- Interactive Prompt ---
            # Print the directory path relative to the starting point
            relative_path = os.path.relpath(root, start_directory)
            
            # Check if there are any image files in this folder to process
            has_images = any(f.lower().endswith(tuple(ALLOWED_EXTENSIONS)) for f in files)
            
            if not has_images:
                print(f"Skipping empty image folder: {relative_path}")
                continue

            response = input(f"\nProcess directory '{relative_path}'? (y/n): ").lower()
            
            if response != 'y':
                print(f"Skipping directory: {relative_path}")
                continue
            # --- End Interactive Prompt ---
        
        
        # Process files within the current root (folder)
        processed_in_folder = 0
        
        for filename in files:
            name, ext = os.path.splitext(filename)
            
            # Check if the file is an image and not the script itself
            if ext.lower() in ALLOWED_EXTENSIONS and filename != os.path.basename(sys.argv[0]):
                
                input_path = os.path.join(root, filename)
                
                print(f"  Processing: {filename}...")

                # Call the core downscale function
                success, message = downscale_image_nearest_neighbor(input_path, divisor)
                
                # Report the result
                if success:
                    print(f"  ✅ {message}.")
                    processed_in_folder += 1
                else:
                    print(f"  ❌ Failed: {message}")

        if processed_in_folder > 0:
            print(f"--- Folder Complete: {processed_in_folder} files processed in {os.path.relpath(root, start_directory)} ---")
            total_processed_count += processed_in_folder


    print(f"\n*** BATCH DOWNGRADE FINISHED ***")
    print(f"Total images processed: {total_processed_count}")


if __name__ == "__main__":
    try:
        # Check Pillow version compatibility
        _ = Image.NEAREST 
        batch_downscale_interactive(SCALE_FACTOR)
    except AttributeError:
        print("\nFATAL ERROR: Your Pillow library version is too old. Please update it ('pip install --upgrade Pillow').")
    except ImportError:
        print("\nFATAL ERROR: The Pillow library is not installed. Please install it ('pip install Pillow').")
    except Exception as e:
        print(f"\nAn unexpected runtime error occurred: {e}")