import os

try:
    import comtypes.client
except Exception:
    print("\ndocx2pdf.py: Import error: comtypes.client")
    input("Install: pip install comtypes\n")


def docx_to_pdf(input_path, output_path=None):
    """
    WordファイルをPDFに変換します。
    成功時は output_path を返し、失敗時は None を返します。
    """
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = 0

    wdFormatPDF = 17

    input_path = os.path.abspath(input_path)
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + ".pdf"
    else:
        output_path = os.path.abspath(output_path)

    print(f"  Converting '{os.path.basename(input_path)}' to PDF...")

    doc = None
    try:
        doc = word.Documents.Open(
            input_path,
            ConfirmConversions=False,
            ReadOnly=True,
            AddToRecentFiles=False,
        )
        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}")
        if doc is not None:
            try:
                doc.Close(False)
            except Exception:
                pass
        return None
    finally:
        word.Quit()


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 docx2pdf.py input.docx [output.pdf]")
        input("\nPress ENTER to terminate>>\n")
        raise SystemExit(1)

    docx_to_pdf(input_path, output_path)
    print("\nProgram execution completed.")
    input("\nPress ENTER to terminate>>\n")
