import os

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


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

    xlTypePDF = 0

    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...")

    workbook = None
    try:
        workbook = excel.Workbooks.Open(input_path, ReadOnly=True)
        workbook.ExportAsFixedFormat(xlTypePDF, output_path)
        workbook.Close(False)
        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 workbook is not None:
            try:
                workbook.Close(False)
            except Exception:
                pass
        return None
    finally:
        excel.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 xlsx2pdf.py input.xlsx [output.pdf]")
        input("\nPress ENTER to terminate>>\n")
        raise SystemExit(1)

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