import os

try:
    import comtypes.client
except Exception:
    print("\npptx2pdf_with_speaker_note.py: Import error: comtypes.client")
    input("Install: pip install comtypes\n")


def pptx_to_pdf_with_notes(input_path, output_path=None):
    """
    PowerPointファイルをスピーカーノート付きでPDFに変換します。
    成功時は output_path を返し、失敗時は None を返します。
    Windows環境かつ Microsoft PowerPoint が必要です。
    """
    powerpoint = None
    presentation = None

    input_path = os.path.abspath(input_path)
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + "_with_notes.pdf"
    else:
        output_path = os.path.abspath(output_path)

    print(f"  Converting '{os.path.basename(input_path)}' to PDF with speaker notes...")

    try:
        if not os.path.exists(input_path):
            print(f"  Error converting '{input_path}' to PDF: file does not exist")
            return None

        if os.path.getsize(input_path) == 0:
            print(f"  Error converting '{input_path}' to PDF: file is empty")
            return None

        # PowerPoint を起動
        powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
        powerpoint.Visible = 1

        # プレゼンテーションを開く
        presentation = powerpoint.Presentations.Open(input_path, WithWindow=False)

        # ExportAsFixedFormat
        # 2 = ppFixedFormatTypePDF
        # 2 = ppFixedFormatIntentPrint
        # 7 = ppPrintOutputNotesPages
        # 1 = ppPrintAll
        presentation.ExportAsFixedFormat(
            output_path,   # Path
            2,             # FixedFormatType: PDF
            2,             # Intent: Print
            False,         # FrameSlides
            7,             # HandoutOrder / OutputType相当: Notes Pages
            False,         # PrintHiddenSlides
            None,          # PrintRange
            1,             # RangeType: All
            "",            # SlideShowName
            True,          # IncludeDocProperties
            False,         # KeepIRMSettings
            True,          # DocStructureTags
            True,          # BitmapMissingFonts
            False,         # UseISO19005_1
        )

        print(f"  Successfully converted to PDF with notes: '{output_path}'")
        return output_path

    except Exception as e:
        print(f"  Error converting '{input_path}' to PDF with notes: {e}")
        return None

    finally:
        if presentation is not None:
            try:
                presentation.Close()
            except Exception:
                pass

        if powerpoint is not None:
            try:
                powerpoint.Quit()
            except Exception:
                pass


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_with_notes_importable.py input.pptx [output.pdf]")
        input("\nPress ENTER to terminate>>\n")
        raise SystemExit(1)

    rc = 0 if pptx_to_pdf_with_notes(input_path, output_path) else 1
    print("\nProgram execution completed.")
    input("\nPress ENTER to terminate>>\n")
    raise SystemExit(rc)
