#pip install weasyprint
#pip install pdfkit
# install https://wkhtmltopdf.org/

import sys
import os

try:
    from weasyprint import HTML
except:
    print(f"Warning: Failed to import weasyprint")
    print(f"Install if you like to use: pip install pango weasyprint")
    HTML = None
try:
    import pdfkit
except:
    print(f"Warning: Failed to import pdfkit")
    print(f"Install if you like to use: pip install pdfkit")
    print(f"  Also install wkhtmltopdf: see https://wkhtmltopdf.org/")
    pdfkit = None


input_path = "peak_fit.html"
output_path = ''

argv = sys.argv
nargs = len(argv)
if nargs > 1:
    input_path = argv[1]
if nargs > 2:
    output_path = argv[2]

if output_path == '':
    output_path = os.path.splitext(input_path)[0] + '.pdf'


def replace_path(path, ext):
    if not path:
        print("Error: 入力パスが空です。", file=sys.stderr)
        sys.exit(1)
    return os.path.splitext(path)[0] + ext

def convert_to_pdf(input_path, output_path = None):
    print()
    print(f"Converting {input_path} to {output_path} ...")

    if not os.path.exists(input_path):
        print(f"Error: ファイル '{input_path}' が存在しません。", file=sys.stderr)
        return False
    if os.path.getsize(input_path) == 0:
        print(f"Error: 入力ファイル '{input_path}' は空です。", file=sys.stderr)
        return False

    if output_path is None:
        output_path = replace_path(input_path, '.pdf')

    if HTML:
        HTML(input_path).write_pdf(output_path)
        print(f"Converted to {output_path} by weasyprint")
    elif pdfkit:
        path_to_wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
        config = pdfkit.configuration(wkhtmltopdf=path_to_wkhtmltopdf)
        pdfkit.from_file(input_path, output_path, configuration=config)
        print(f"Converted to {output_path} by pdfkit")
    else:
        print(f"\nNo html2pdf library available. Install weasyprint or pdfkit\n")


def main():
    convert_to_pdf(input_path, output_path)

    input("\nPress ENTER to terminate>>")

if __name__ == "__main__":
    main()