import os
import sys
import glob
try:
    import comtypes
    from comtypes import client
except:
    print("\npptx2pdf_recursive.py: Import error: comtypes")
    input("Install: pip install comtypes\n")


# デフォルト値の設定
infile = '41-01-search_MP.pptx'
out_dir = 'images'
image_format = 'png'

# コマンドライン引数の解析
nargv = len(sys.argv)
if nargv >= 2:
    infile = sys.argv[1]
if nargv >= 3:
    out_dir = sys.argv[2]
if nargv >= 4:
    image_format = sys.argv[3]

def export_img(fname, out_dir, image_format):
    """
    指定されたPowerPointファイルを画像としてエクスポートします。
    
    Args:
        fname (str): PowerPointファイルのパス (相対パスまたは絶対パス)。
        out_dir (str): 画像を保存する出力ディレクトリのパス。
        image_format (str): エクスポートする画像の形式 (例: 'png', 'jpg')。
    """

    application = None # PowerPointアプリケーションオブジェクトの初期化
    try:
        # PowerPointアプリケーションのCOMオブジェクトを作成
        print()
        print(f"Create PowerPoiint.Application object")
        application = client.CreateObject("PowerPoint.Application")
        application.Visible = True # PowerPointアプリケーションを可視化

        # 入力ファイルの絶対パスを解決
        # os.path.abspath() を使用することで、fnameが相対パスでも絶対パスでも
        # 正しいフルパスに変換されます。
        full_pptx_path = os.path.abspath(fname)
        
        print(f"Open [{full_pptx_path}]")
        # PowerPointファイルを開く
        # ここで解決済みの絶対パスを使用します。
        presentation = application.Presentations.Open(full_pptx_path)

        # 出力ディレクトリの絶対パスを解決し、存在しない場合は作成
        export_path = os.path.abspath(out_dir)
        print(f"out_dir: {out_dir}")
        if not os.path.exists(export_path):
            os.makedirs(export_path) # ディレクトリが存在しない場合は作成
            print(f"   Created [{out_dir}]")
    
        print(f"Exporting as images [{image_format}] to [{export_path}]")
        # 画像としてエクスポート
        presentation.Export(export_path, FilterName=image_format)

        presentation.Close() # プレゼンテーションを閉じる
        print("Presentation closed.")

    except Exception as e:
        print(f"Error during export: {e}", file=sys.stderr)
        # COMErrorの詳細情報を表示
        # comtypes.COMError を使用するように修正
        if isinstance(e, comtypes.COMError): 
            print(f"COMError details: {e.args}", file=sys.stderr)
    finally:
        # PowerPointアプリケーションを終了
        if application is not None:
            application.Quit()
            print("PowerPoint application quit.")

def rename_img(out_dir):
    """
    エクスポートされた画像ファイルの名前を変更します。
    PowerPointが生成するデフォルト名 'スライドN.png' を 'slideN.png' に変更します。
    
    Args:
        out_dir (str): 画像が保存されているディレクトリのパス。
    """
    # 出力ディレクトリの絶対パスを解決
    full_out_dir = os.path.abspath(out_dir)
    
    # 'スライド*.png' パターンに一致するファイルを検索
    file_list = glob.glob(os.path.join(full_out_dir, "スライド*.png"))
    
    print(f"Renaming images in [{full_out_dir}]...")
    for fname in file_list:
        # 新しいファイル名を生成 (例: 'スライド1.png' -> 'slide1.png')
        new_fname = fname.replace('スライド', 'slide').lower()
        try:
            os.rename(fname, new_fname)
            print(f"  Renamed '{os.path.basename(fname)}' to '{os.path.basename(new_fname)}'")
        except OSError as e:
            print(f"Error renaming '{fname}': {e}", file=sys.stderr)

if __name__ == '__main__':
    # メイン処理の実行
    export_img(infile, out_dir, image_format)
    rename_img(out_dir)
    
    input("\nPress ENTER to terminate>>\n")
