"""
PPTX to PDF converter using Windows COM.
"""

import os
from pathlib import Path


def convert_pptx_to_pdf(pptx_path: str, pdf_path: str, powerpoint) -> bool:
    presentation = powerpoint.Presentations.Open(pptx_path, WithWindow=False)
    presentation.SaveAs(pdf_path, 32)  # 32 = ppSaveAsPDF
    presentation.Close()
    return True


def convert_all_pptx_in_folder(folder: Path, delete_originals: bool = True) -> tuple[int, int]:
    """
    Convert all PPTX files in a folder (recursively) to PDF.
    
    Returns:
        Tuple of (converted_count, failed_count)
    """
    try:
        import comtypes.client
    except ImportError:
        print("Error: comtypes is required for PPTX to PDF conversion.")
        print("Install it with: pip install comtypes")
        return 0, 0

    if not folder.exists():
        print(f"Error: Folder '{folder}' does not exist!")
        return 0, 0

    pptx_files = list(folder.rglob("*.pptx"))

    if not pptx_files:
        print("No .pptx files found.")
        return 0, 0

    print(f"Found {len(pptx_files)} PowerPoint files to convert.\n")

    print("Starting Microsoft PowerPoint...")
    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")

    converted = 0
    failed = 0

    try:
        for pptx_path in pptx_files:
            pdf_path = pptx_path.with_suffix(".pdf")
            print(f"Converting: {pptx_path.name}")

            if convert_pptx_to_pdf(str(pptx_path), str(pdf_path), powerpoint):
                if pdf_path.exists():
                    if delete_originals:
                        os.remove(pptx_path)
                        print(f"  -> Converted and deleted original")
                    else:
                        print(f"  -> Converted (keeping original)")
                    converted += 1
                else:
                    print(f"  -> PDF not created, keeping original")
                    failed += 1
            else:
                failed += 1

    finally:
        print("\nClosing PowerPoint...")
        powerpoint.Quit()

    print(f"\n{'='*50}")
    print(f"Conversion complete!")
    print(f"  Successfully converted: {converted}")
    print(f"  Failed: {failed}")
    print(f"{'='*50}")

    return converted, failed
