import os

try:
    import comtypes.client
except Exception:
    print("\npptx2pdf.py: Import error: comtypes.client")
    input("Install: pip install comtypes\n")


def pptx_to_pdf(input_path, output_path=None):
    """
    PowerPointファイルをPDFに変換します。
    成功時は output_path を返し、失敗時は None を返します。
    """
    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
    powerpoint.Visible = 1

    input_path = os.path.abspath(input_path)
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + ".pdf"
    else:
        output_path = os.path.abspath(output_path)

    print(f"  Attempting to open PowerPoint file: '{input_path}'")

    presentation = None
    try:
        presentation = powerpoint.Presentations.Open(input_path, WithWindow=False)
        presentation.SaveAs(output_path, 32)
        presentation.Close()
        print(f"  Successfully converted to PDF: '{output_path}'")
        return output_path
    except Exception as e:
        print(f"  Error converting '{input_path}' to PDF: {e}")
        if presentation is not None:
            try:
                presentation.Close()
            except Exception:
                pass
        return None
    finally:
        powerpoint.Quit()


if __name__ == "__main__":
    import sys

    input_path = sys.argv[1] if len(sys.argv) > 1 else None
    output_path = sys.argv[2] if len(sys.argv) > 2 else None

    if not input_path:
        print("Usage: python pptx2pdf.py input.pptx [output.pdf]")
        input("\nPress ENTER to terminate>>\n")
        raise SystemExit(1)

    pptx_to_pdf(input_path, output_path)
    print("\nProgram execution completed.")
    input("\nPress ENTER to terminate>>\n")
