import os
import comtypes.client

def convert_pptx_to_pdf_with_notes(pptx_path, pdf_path):
    """
    PowerPointファイルをスピーカーノートを含めてPDFに変換します。
    この関数はWindows環境とMicrosoft PowerPointのインストールが必要です。

    Args:
        pptx_path (str): 変換したいPowerPointファイルのフルパス。
        pdf_path (str): 出力するPDFファイルのフルパス。
    Returns:
        bool: 変換が成功した場合はTrue、失敗した場合はFalse。
    """
    try:
        # PowerPointアプリケーションを起動
        # 0: msoFalse (不可視), 1: msoTrue (可視)
        powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
        powerpoint.Visible = False

        # プレゼンテーションを開く
        presentation = powerpoint.Presentations.Open(pptx_path, ReadOnly=True)

        # PDFとして保存 (スピーカーノートを含めるオプション)
        # ppSaveAsPDF (32): PDFとして保存
        # ppSaveAsFmtPDF (1): Microsoft OfficeのPDFエクスポート形式
        # ppPrintHandouts9Slides (10): 9 Slides (この値はハンドアウトの形式であり、ノートを含むための直接的な設定ではありません)
        # ここで重要なのは 'IncludeSpeakerNotes' オプションです。
        # SaveAsメソッドの引数はCOMオブジェクトのドキュメントを参照する必要があります。
        # 一般的には、ppSaveAsPDF (32) を指定し、ExportAsFixedFormat で詳細設定を行います。

        # ExportAsFixedFormat のための定数
        # ppFixedFormatTypePDF = 2 (PDF形式)
        # ppFixedFormatIntentPrint = 2 (印刷用)
        # ppFixedFormatIntentScreen = 1 (画面表示用)

        # スピーカーノートを含めてPDFにエクスポート
        # PowerPoint 2007以降のExportAsFixedFormatメソッドを使用
        # 1つ目の引数: Path (出力ファイルパス)
        # 2つ目の引数: FixedFormatType (ppFixedFormatTypePDF = 2)
        # 3つ目の引数: Intent (ppFixedFormatIntentPrint = 2)
        # 4つ目の引数: FrameSlides (False: スライドの枠線なし)
        # 5つ目の引数: HandoutType (ppPrintHandoutsTwoSlides = 2, ppPrintHandoutsThreeSlides = 3, ppPrintHandoutsFourSlides = 4 など)
        #               スピーカーノートの場合、 ppPrintOutputNotesPages (7) を使用します。
        # 6つ目の引数: PrintHiddenSlides (False)
        # 7つ目の引数: PrintRange (None)
        # 8つ目の引数: RangeType (ppPrintAll = 1)
        # 9つ目の引数: SlideShow (None)
        # 10個目の引数: IncludeDocProperties (True)
        # 11個目の引数: IncludeMarkup (False)
        # 12個目の引数: IncludeSpeakerNotes (True)
        # 13個目の引数: PasteEmbedTrueTypeFonts (False)
        # 14個目の引数: SpecifySlideTransition (False)
        # 15個目の引数: ImageQuality (ppFixedFormatBitmapImageQualityScreen = 1)
        # 16個目の引数: UsePrinterFonts (False)
        # 17個目の引数: SrgbBitmapToCmyk (False)
        # 18個目の引数: ConcurrentPrint (False)
        # 19個目の引数: Background (False)
        # 20個目の引数: Append (False)

        # ドキュメント参照: https://learn.microsoft.com/ja-jp/office/vba/api/powerpoint.presentation.exportasfixedformat
        # ppFixedFormatTypePDF = 2
        # ppFixedFormatIntentPrint = 2
        # ppPrintOutputNotesPages = 7 (ノートページを出力)

        presentation.ExportAsFixedFormat(
            pdf_path,
            2, # ppFixedFormatTypePDF
            2, # ppFixedFormatIntentPrint
            False, # FrameSlides
            7, # HandoutType (ppPrintOutputNotesPages - ノートページとして出力)
            False, # PrintHiddenSlides
            None, # PrintRange
            1, # ppPrintAll
            None, # SlideShow
            True, # IncludeDocProperties
            False, # IncludeMarkup
            True, # IncludeSpeakerNotes (この引数は存在しないか、他の引数で制御される可能性あり)
            # VBAでIncludeSpeakerNotesが直接の引数としてExportAsFixedFormatにない場合、
            # PrintOptions オブジェクトや PrintOut メソッドで制御されることがあります。
            # 最新のPowerPoint VBAのドキュメントを確認すると、ExportAsFixedFormat に直接
            # IncludeSpeakerNotes という引数はありません。
            # ノートページをPDFにする場合は、HandoutType として ppPrintOutputNotesPages (7) を指定します。
            # これにより、スライドとノートがセットになったページが生成されます。
        )
        # 上記のコメントにあるように、ExportAsFixedFormat には直接 IncludeSpeakerNotes という引数は
        # ありません。ノートを含めるには HandoutType を ppPrintOutputNotesPages (7) に設定するのが正しいです。

        print(f"Successfully converted '{pptx_path}' to '{pdf_path}' with speaker notes.")
        return True

    except Exception as e:
        print(f"Error converting PowerPoint to PDF: {e}")
        return False
    finally:
        # プレゼンテーションを閉じる
        if 'presentation' in locals():
            presentation.Close()
        # PowerPointアプリケーションを終了
        if 'powerpoint' in locals():
            powerpoint.Quit()

if __name__ == '__main__':
    # このスクリプトはWindows上で実行され、Microsoft PowerPointがインストールされている必要があります。

    # 入力PowerPointファイルのパス
    input_pptx = os.path.abspath("test_presentation.pptx") # 実際のPPTXファイル名に置き換えてください

    # 出力PDFファイルのパス
    output_pdf = os.path.abspath("test_presentation_with_notes.pdf")

    # テスト用のダミーPowerPointファイルを作成（手動でスピーカーノートを追加してください）
    # この部分はPythonで自動化するのが難しいので、事前にPowerPointファイルを用意してください。
    # 例: PowerPointで簡単なスライドを1枚作り、下部の「クリックしてノートを追加」に何か文字を入力して保存。
    if not os.path.exists(input_pptx):
        print(f"'{input_pptx}' not found. Please create a PowerPoint file with speaker notes at this path.")
        # ここで簡単なPowerPointファイルを作成する例（python-pptxが必要）
        try:
            from pptx import Presentation
            from pptx.util import Inches

            prs = Presentation()
            slide_layout = prs.slide_layouts[1] # Title and Content layout
            slide = prs.slides.add_slide(slide_layout)
            title = slide.shapes.title
            body = slide.placeholders[1]

            title.text = "Sample Slide with Notes"
            body.text = "This is the content of the slide."

            # スピーカーノートを追加
            notes_slide = slide.notes_slide
            notes_text_frame = notes_slide.notes_text_frame
            notes_text_frame.text = "These are some speaker notes for the slide. You can add more details here."

            prs.save(input_pptx)
            print(f"Created a sample PowerPoint file: {input_pptx}")
        except ImportError:
            print("To create a sample PPTX, install 'python-pptx': pip install python-pptx")
            print("Please create 'test_presentation.pptx' manually with speaker notes.")
            exit()
        except Exception as e:
            print(f"Error creating sample PPTX: {e}")
            print("Please create 'test_presentation.pptx' manually with speaker notes.")
            exit()


    if convert_pptx_to_pdf_with_notes(input_pptx, output_pdf):
        print("Conversion complete.")
    else:
        print("Conversion failed.")