import os

try:
    from weasyprint import HTML
except Exception:
    print("Warning in html2pdf.py: Failed to import weasyprint")
    print("Install if you want to use it: pip install weasyprint")
    HTML = None

try:
    import pdfkit
except Exception:
    print("Warning in html2pdf.py: Failed to import pdfkit")
    print("Install if you want to use it: pip install pdfkit")
    print("Also install wkhtmltopdf: https://wkhtmltopdf.org/")
    pdfkit = None


def html_to_pdf(input_path, output_path=None):
    """
    HTMLファイルをPDFに変換します。
    成功時は output_path を返し、失敗時は None を返します。
    優先順位:
      1. weasyprint
      2. pdfkit + wkhtmltopdf
    """
    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...")

    try:
        if not os.path.exists(input_path):
            print(f"  Error converting '{input_path}' to PDF: file does not exist")
            return None

        if os.path.getsize(input_path) == 0:
            print(f"  Error converting '{input_path}' to PDF: file is empty")
            return None

        if HTML is not None:
            HTML(filename=input_path).write_pdf(output_path)
            print(f"  Successfully converted to PDF: '{output_path}'")
            return output_path

        if pdfkit is not None:
            wkhtmltopdf_path = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
            config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path)
            pdfkit.from_file(input_path, output_path, configuration=config)
            print(f"  Successfully converted to PDF: '{output_path}'")
            return output_path

        print("  Error converting to PDF: no available backend (weasyprint or pdfkit)")
        return None

    except Exception as e:
        print(f"  Error converting '{input_path}' to PDF: {e}")
        return None


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 html2pdf.py input.html [output.pdf]")
        input("\nPress ENTER to terminate>>\n")
        raise SystemExit(1)

    html_to_pdf(input_path, output_path)
    print("\nProgram execution completed.")
    input("\nPress ENTER to terminate>>\n")
