"""
This script is offered as a complimentary tool for BlueMail users to facilitate the conversion of PST files to MBOX format. 
While we provide this utility free of charge, it is delivered "as-is" without any warranties, expressed or implied. 
BlueMail and its affiliates assume no responsibility or liability for any damages, issues, or data loss that may arise from its use. 
By using this script, you acknowledge that it is entirely at your own risk and discretion. 
Please ensure you have proper backups and review results before proceeding with any critical actions.
"""

import pypff
import mailbox
import os

def read_pst(file_path):
    """Reads a PST file using pypff and returns the PST object."""
    pst_file = pypff.file()
    pst_file.open(file_path)
    return pst_file

def convert_pst_to_mbox(pst_file, mbox_file_path):
    """
    Converts a PST file object into an MBOX file.
    
    Arguments:
    pst_file: The opened PST file object.
    mbox_file_path: The path where the output MBOX file will be saved.
    """
    # Create MBOX writer
    mbox = mailbox.mbox(mbox_file_path)
    
    # Get the root folder of the PST file
    root_folder = pst_file.get_root_folder()
    
    # Process all folders and subfolders in the PST file
    process_folder(root_folder, mbox)
    
    # Save and close the MBOX file
    mbox.flush()

def process_folder(folder, mbox):
    """
    Processes a PST folder and its subfolders, saving emails to the MBOX file.
    
    Arguments:
    folder: The current PST folder to process.
    mbox: The MBOX object to store the emails.
    """
    # Iterate over all messages in the folder
    for message in folder.sub_messages:
        mbox_msg = mailbox.mboxMessage()

        # Add subject, sender, and date headers (if available)
        if message.subject:
            mbox_msg["Subject"] = message.subject
        if message.sender_name:
            mbox_msg["From"] = message.sender_name
        if message.delivery_time:
            mbox_msg["Date"] = str(message.delivery_time)
        
        # Add the email body
        mbox_msg.set_payload(message.plain_text_body)
        
        # Add the message to the MBOX
        mbox.add(mbox_msg)
    
    # Process all subfolders recursively
    for subfolder in folder.sub_folders:
        process_folder(subfolder, mbox)

def main(pst_file_path, mbox_output_path):
    """
    Main function that performs the conversion of PST to MBOX.
    
    Arguments:
    pst_file_path: The path to the PST file.
    mbox_output_path: The path to save the resulting MBOX file.
    """
    # Check if the PST file exists
    if not os.path.exists(pst_file_path):
        print(f"PST file not found: {pst_file_path}")
        return

    # Open the PST file
    pst_file = read_pst(pst_file_path)

    # Convert PST to MBOX
    print(f"Converting PST file '{pst_file_path}' to MBOX file '{mbox_output_path}'...")
    convert_pst_to_mbox(pst_file, mbox_output_path)
    print(f"Conversion complete. MBOX file saved to: {mbox_output_path}")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        print("Usage: python convert_pst_to_mbox.py <pst_file_path> <mbox_output_path>")
    else:
        pst_file_path = sys.argv[1]
        mbox_output_path = sys.argv[2]
        main(pst_file_path, mbox_output_path)
