import subprocess
import os
from typing import Optional
from metadata_cleaner.logs.logger import logger

def remove_video_metadata(file_path: str, output_path: Optional[str] = None) -> Optional[str]:
    """
    Removes metadata from a video file using FFmpeg.

    This function re-encodes the video using libx264 for video and aac for audio,
    stripping all metadata from the output file.

    Parameters:
        file_path (str): Path to the input video file.
        output_path (Optional[str]): Destination path for the cleaned video.
                                     If None, a new file name is generated by appending '_cleaned'
                                     before the file extension.

    Returns:
        Optional[str]: The path to the cleaned video if successful; otherwise, None.
    """
    try:
        if not output_path:
            base, ext = os.path.splitext(file_path)
            output_path = f"{base}_cleaned{ext}"

        command = [
            "ffmpeg", "-i", file_path, "-map_metadata", "-1",
            "-c:v", "libx264", "-c:a", "aac", output_path, "-y"
        ]
        subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
        return output_path

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