from docx import Document
from typing import Optional
from metadata_cleaner.logs.logger import logger

def remove_docx_metadata(file_path: str, output_path: Optional[str] = None) -> Optional[str]:
    """
    Removes metadata from a DOCX file by clearing its core properties.

    Parameters:
        file_path (str): The path to the DOCX file.
        output_path (Optional[str]): The destination path for the cleaned file.
                                     If None, a new file name is generated by inserting '_cleaned'
                                     before the file extension.

    Returns:
        Optional[str]: The path to the cleaned DOCX file if successful; otherwise, None.
    """
    try:
        doc = Document(file_path)

        # Clear core properties
        doc.core_properties.author = ""
        doc.core_properties.title = ""
        doc.core_properties.keywords = ""
        doc.core_properties.comments = ""

        if not output_path:
            base, ext = file_path.rsplit(".", 1)
            output_path = f"{base}_cleaned.{ext}"

        doc.save(output_path)
        return output_path

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