#!/usr/bin/env python3
"""
HTML to PDF converter — WeasyPrint (primary) with pdfkit fallback.
Usage: python3 html2pdf.py <input.html> <output.pdf> [orientation]
  orientation: Portrait (default) or Landscape
"""
import sys
import os
import re

def inject_page_style(html: str, orientation: str) -> str:
    """Inject @page CSS for page numbers and margins into HTML."""
    size = 'A4 landscape' if orientation.lower() == 'landscape' else 'A4'
    css = f"""
<style id="__page_style__">
@page {{
  size: {size};
  margin: 10mm 12mm 18mm 12mm;
  @bottom-right {{
    content: "第 " counter(page) " / " counter(pages) " 頁";
    font-family: 'Noto Sans CJK TC', 'Microsoft JhengHei', Arial, sans-serif;
    font-size: 10pt;
    font-weight: bold;
    color: #000;
  }}
  @bottom-left {{
    content: "智新資通 資安檢測服務";
    font-family: 'Noto Sans CJK TC', 'Microsoft JhengHei', Arial, sans-serif;
    font-size: 9pt;
    color: #000;
  }}
}}
</style>"""
    # Inject before </head>, or before <body> if no </head>
    if '</head>' in html:
        return html.replace('</head>', css + '\n</head>', 1)
    return css + html


def render_weasyprint(html_path: str, pdf_path: str, orientation: str) -> None:
    import weasyprint
    with open(html_path, encoding='utf-8') as f:
        html = f.read()
    html = inject_page_style(html, orientation)
    weasyprint.HTML(string=html, base_url=os.path.dirname(html_path)).write_pdf(pdf_path)


def render_pdfkit(html_path: str, pdf_path: str, orientation: str) -> None:
    import pdfkit
    options = {
        'encoding': 'UTF-8',
        'page-size': 'A4',
        'orientation': orientation,
        'margin-top': '10mm',
        'margin-right': '12mm',
        'margin-bottom': '10mm',
        'margin-left': '12mm',
        'no-outline': None,
        'enable-local-file-access': None,
        'enable-javascript': None,
        'javascript-delay': '2000',
    }
    pdfkit.from_file(html_path, pdf_path, options=options)


def main():
    if len(sys.argv) < 3:
        print("Usage: html2pdf.py <input.html> <output.pdf> [Landscape|Portrait]", file=sys.stderr)
        sys.exit(1)

    html_path   = sys.argv[1]
    pdf_path    = sys.argv[2]
    orientation = sys.argv[3] if len(sys.argv) > 3 else 'Portrait'

    try:
        render_weasyprint(html_path, pdf_path, orientation)
        print(f"OK (WeasyPrint): {pdf_path}")
    except Exception as e:
        print(f"WeasyPrint failed ({e}), falling back to pdfkit…", file=sys.stderr)
        render_pdfkit(html_path, pdf_path, orientation)
        print(f"OK (pdfkit): {pdf_path}")


if __name__ == '__main__':
    main()
