import os
import sys
import datetime
try:
    import comtypes.client
except:
    print("\npptx2pdf_recursive.py: Import error: comtypes.client")
    input("Install: pip install comtypes\n")


root_dir = "."  # 現在のディレクトリ
max_level = -1  # 無制限

# python script.py [root_dir] [max_level]
if len(sys.argv) > 1: root_dir = sys.argv[1]
if len(sys.argv) > 2: max_level = sys.argv[2]
try:
    max_level = int(max_level)
except ValueError:
    print(f"Error: Invalid max_level '{max_level}'.")
    exit()


def docx_to_pdf(input_path, output_path=None):
    """
    WordファイルをPDFに変換します。
    """
    # Wordのアプリケーションを起動
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = 0  # アプリを表示しない場合は 0

    # PDF保存形式の定数 (wdFormatPDF)
    # Microsoft Word Object Library Referenceより
    wdFormatPDF = 17 

    # 出力先のパスを指定
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + ".pdf"

    print(f"  Converting '{os.path.basename(input_path)}' to PDF...")
    
    try:
        # ドキュメントを開く
        doc = word.Documents.Open(input_path, ConfirmConversions=False, ReadOnly=True, AddToRecentFiles=False)

        # PDFとして保存
        doc.SaveAs(output_path, FileFormat=wdFormatPDF)
        doc.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}")
        return None
    finally:
        # Wordアプリケーションを終了
        word.Quit()

def convert_docx_files(root_dir, max_level=-1):
    """
    指定されたディレクトリからWordファイルを再帰的に検索し、必要に応じてPDFに変換します。
    """
    if not os.path.isdir(root_dir):
        print(f"Error: Root directory '{root_dir}' does not exist.")
        return

    root_dir_abs = os.path.abspath(root_dir)
    print(f"Searching for .docx files in '{root_dir_abs}' (max_level: {max_level})...")
    
    for dirpath, dirnames, filenames in os.walk(root_dir_abs):
        # 現在のディレクトリの深さを計算
        current_level = dirpath.count(os.sep) - root_dir_abs.count(os.sep)
        
        if max_level != -1 and current_level >= max_level:
            # 指定された深さ制限を超えた場合、このブランチはスキップ
            del dirnames[:] # これにより、os.walkがこのディレクトリの下に進まないようにする
            continue

        for filename in filenames:
            if filename.lower().endswith(".docx"):
                docx_full_path = os.path.join(dirpath, filename)
                pdf_full_path = os.path.splitext(docx_full_path)[0] + ".pdf"

                needs_conversion = False

                if not os.path.exists(pdf_full_path):
                    print(f"'{os.path.basename(pdf_full_path)}' does not exist. Converting...")
                    needs_conversion = True
                else:
                    docx_timestamp = os.path.getmtime(docx_full_path)
                    pdf_timestamp = os.path.getmtime(pdf_full_path)

                    if docx_timestamp > pdf_timestamp:
                        print(f"'{os.path.basename(pdf_full_path)}' is older than '{os.path.basename(docx_full_path)}'. Converting...")
                        needs_conversion = True
                    else:
                        print(f"'{os.path.basename(docx_full_path)}' is up to date. Skipping conversion.")

                if needs_conversion:
                    docx_to_pdf(docx_full_path, pdf_full_path)
    
    print("\nPDF conversion process finished.")
    input("\n>>Press ENTER to terminate>>\n")
    

if __name__ == "__main__":
    convert_docx_files(root_dir, max_level)
    print("\nProgram execution completed.")