import os
from PIL import Image

# --- Configuration ---
SCALE_FACTOR = 2  # Divisor: The 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_current_directory(divisor):
    """Finds all allowed image files in the current directory and downscales them, overwriting originals."""
    
    # --- SAFETY CHECK ---
    print("\n\n!!! WARNING: THIS SCRIPT WILL OVERWRITE YOUR ORIGINAL FILES !!!")
    input("Press Enter to continue or Ctrl+C to stop and make a backup...")
    # --------------------
    
    current_directory = os.getcwd()
    file_list = os.listdir(current_directory)
    
    print(f"\n--- Starting Batch Downscale (1/{divisor} size) ---")
    print(f"Directory: {current_directory}\n")
    
    processed_count = 0
    
    for filename in file_list:
        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(__file__):
            
            input_path = os.path.join(current_directory, filename)
            
            print(f"Processing: {filename}...")

            # Call the core downscale function, passing the input path as both source and destination
            success, message = downscale_image_nearest_neighbor(input_path, SCALE_FACTOR)
            
            # Report the result
            if success:
                print(f"  ✅ {message}.")
                processed_count += 1
            else:
                print(f"  ❌ Failed: {message}")

    print(f"\n--- Batch Complete: {processed_count} files processed. ---")


if __name__ == "__main__":
    try:
        # Check Pillow version compatibility
        _ = Image.NEAREST 
        batch_downscale_current_directory(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}")