from PIL import Image
import piexif
import os
from typing import Optional
from metadata_cleaner.core import metadata_filter
from metadata_cleaner.logs.logger import logger

def remove_image_metadata(file_path: str, output_path: Optional[str] = None, config_file: Optional[str] = None) -> Optional[str]:
    """
    Removes metadata from an image file using selective filtering.

    This function uses Pillow to open the image and piexif to load and dump EXIF data.
    It applies filtering rules (from a configuration file if provided) to selectively remove or modify EXIF fields.

    Parameters:
        file_path (str): Path to the image file.
        output_path (Optional[str]): Destination path for the cleaned image.
                                     If None, a new file name is generated by appending '_cleaned' before the extension.
        config_file (Optional[str]): Path to a JSON configuration file for selective metadata filtering.
    
    Returns:
        Optional[str]: The path to the cleaned image if successful; otherwise, None.
    """
    try:
        img = Image.open(file_path)
        
        # Retrieve existing EXIF data if available
        exif_bytes = img.info.get('exif')
        if exif_bytes:
            exif_dict = piexif.load(exif_bytes)
        else:
            exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "thumbnail": None}
        
        # Load filtering rules (from config file if provided, else use defaults)
        rules = metadata_filter.load_filter_rules(config_file)
        
        # Filter the EXIF data based on the rules
        filtered_exif = metadata_filter.filter_exif_data(exif_dict, rules)
        new_exif_bytes = piexif.dump(filtered_exif)
        
        # Determine output path if not provided
        if not output_path:
            base, ext = os.path.splitext(file_path)
            output_path = f"{base}_cleaned{ext}"
        
        # Save the image with the filtered EXIF data
        img.save(output_path, exif=new_exif_bytes)
        return output_path

    except Exception as e:
        logger.error(f"Error removing metadata from image {file_path}: {e}", exc_info=True)
        return None
