from pypdf import PdfReader, PdfWriter
import os
from typing import Optional
from metadata_cleaner.logs.logger import logger

def remove_pdf_metadata(file_path: str, output_path: Optional[str] = None) -> Optional[str]:
    """
    Removes metadata from a PDF file by copying its pages into a new PDF without metadata.

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

    Returns:
        Optional[str]: The path to the cleaned PDF if successful; otherwise, None.
    """
    try:
        reader = PdfReader(file_path)
        writer = PdfWriter()

        # Copy each page to the writer
        for page in reader.pages:
            writer.add_page(page)

        # Clear any existing metadata
        writer.add_metadata({})

        if not output_path:
            base, ext = os.path.splitext(file_path)
            output_path = f"{base}_cleaned{ext}"

        with open(output_path, "wb") as f:
            writer.write(f)

        return output_path

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