import os
import sys
import datetime
try:
    import comtypes.client
except:
    print("\npptx2pdf_recursive.py: Import error: comtypes")
    input("Install: pip install comtypes\n")

infile = ""
outfile = None

if len(sys.argv) > 1: infile = sys.argv[1]
if len(sys.argv) > 2: outfile = sys.argv[2]


def pptx_to_pdf(input_path, output_path=None):
    """
    PowerPointファイルをPDFに変換します。
    """

    # 入力パスを絶対パスに変換し、セパレータを修正
    input_path = os.path.abspath(input_path)

    # 出力パスが指定されている場合は同様に絶対パスに変換
    if output_path is not None:
        output_path = os.path.abspath(output_path)

    # PowerPointのアプリケーションを起動
    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
    powerpoint.Visible = 1

    # 出力先のパスを指定
    if output_path is None:
        # 入力パスから出力パスを自動生成
        output_path = os.path.splitext(input_path)[0] + ".pdf"

    print(f"  入力ファイル: {input_path}")
    print(f"  出力ファイル: {output_path}")

    try:
        # プレゼンテーションを開く
        presentation = powerpoint.Presentations.Open(input_path, WithWindow=False)

        # PDFとして保存（フォーマット番号 32 = PDF）
        presentation.SaveAs(output_path, 32)
        presentation.Close()
        print(f"  PDFに正常に変換しました: '{output_path}'")
        return output_path
    except Exception as e:
        print(f"  エラーが発生しました: '{input_path}' をPDFに変換できませんでした: {e}")
        return None
    finally:
        # PowerPointアプリケーションを終了
        powerpoint.Quit()


if __name__ == "__main__":
    if infile == "":
        print("エラー: 入力ファイルが指定されていません。")
        print("使い方: python script_name.py <入力ファイルパス> [<出力ファイルパス>]")
    else:
        pptx_to_pdf(infile, outfile)
    
    print("\nプログラムの実行が完了しました。")
    input("\nENTERキーを押して終了>>\n")