#!/usr/bin/env python3
"""
Convert HTML to PDF using Headless Chrome/Chromium via Selenium
If no browser available, creates printable HTML version
"""

import os
import sys
from datetime import datetime

# Check for available tools
try:
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.chrome.service import Service
    SELENIUM_AVAILABLE = True
except ImportError:
    SELENIUM_AVAILABLE = False
    print("⚠️  Selenium not available")

try:
    import pdfkit
    PDFKIT_AVAILABLE = True
except ImportError:
    PDFKIT_AVAILABLE = False
    print("⚠️  pdfkit not available")

def convert_html_to_pdf(html_file, output_pdf):
    """
    Convert HTML file to PDF
    
    Priority order:
    1. Selenium + Headless Chrome (best quality)
    2. wkhtmltopdf via pdfkit
    3. Print-friendly HTML fallback
    """
    
    # Method 1: Selenium with Headless Chrome
    if SELENIUM_AVAILABLE:
        print("🔄 Attempting conversion with Selenium + Headless Chrome...")
        try:
            chrome_options = Options()
            chrome_options.add_argument("--headless")
            chrome_options.add_argument("--no-sandbox")
            chrome_options.add_argument("--disable-dev-shm-usage")
            chrome_options.add_argument("--pdf")
            
            driver = webdriver.Chrome(options=chrome_options)
            page = driver.page
            
            # Load HTML file
            abs_path = os.path.abspath(html_file)
            page.goto(f"file://{abs_path}", waitUntil="networkidle0")
            
            # Generate PDF
            page.pdf(path=output_pdf, format="A4", margin={"top": "10mm", "bottom": "10mm"})
            
            driver.quit()
            print(f"✅ Successfully created PDF with Selenium!")
            return True
            
        except Exception as e:
            print(f"❌ Selenium method failed: {e}")
    
    # Method 2: wkhtmltopdf via pdfkit
    if PDFKIT_AVAILABLE and os.path.exists("/usr/bin/wkhtmltopdf"):
        print("🔄 Attempting conversion with wkhtmltopdf...")
        try:
            options = {
                'page-size': 'A4',
                'margin-top': '10mm',
                'margin-right': '10mm',
                'margin-bottom': '10mm',
                'margin-left': '10mm',
                'encoding': 'UTF-8',
                'no-outline': None
            }
            pdfkit.from_file(html_file, output_pdf, options=options)
            print(f"✅ Successfully created PDF with wkhtmltopdf!")
            return True
            
        except Exception as e:
            print(f"❌ wkhtmltopdf method failed: {e}")
    
    # Fallback: Print-ready HTML version
    print("💡 Creating print-ready HTML version as alternative...")
    html_base = html_file.replace('.html', '')
    print_html = f"{html_base}_printable.html"
    
    with open(html_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add print-specific styles
    print_styles = """
    <style>
        @media print {
            body { background: white; }
            .container { max-width: 100%; padding: 20px; }
            .header { background: #DC2626 !important; color: white !important; }
            .section-card { break-inside: avoid; box-shadow: none !important; border: 1px solid #ddd !important; }
            .stats-grid { display: block; }
            .stat-card { display: inline-block; width: auto; margin: 10px; }
            .reference-section { background: #F0FDF4 !important; }
            table { width: 100%; font-size: 10pt !important; }
            th, td { border: 1px solid #ddd !important; padding: 5px !important; }
            a { text-decoration: none; color: inherit; }
        }
    </style>
    """
    
    # Insert before </head>
    content = content.replace('</head>', print_styles + '</head>')
    
    with open(print_html, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✅ Created printable HTML version: {print_html}")
    print("\n📝 To convert manually:")
    print("   1. Open the HTML file in browser")
    print("   2. Press Ctrl+P (or Cmd+P on Mac)")
    print("   3. Select 'Save as PDF'")
    print("   4. Choose A4 paper size and proper margins")
    
    return print_html

if __name__ == "__main__":
    # Get input/output files
    html_input = "/root/.openclaw/workspace/daily_brief/ANALISA_KETAHANAN_PANGAN_2026.html"
    pdf_output = "/root/.openclaw/workspace/daily_brief/ANALISA_KETAHANAN_PANGAN_2026.pdf"
    
    if len(sys.argv) > 1:
        html_input = sys.argv[1]
    if len(sys.argv) > 2:
        pdf_output = sys.argv[2]
    
    print(f"📄 Converting: {html_input}")
    print(f"📑 Output: {pdf_output}\n")
    
    result = convert_html_to_pdf(html_input, pdf_output)
    
    if result:
        print(f"\n✅ Conversion successful!")
        if isinstance(result, str):
            print(f"📁 File saved at: {result}")
        else:
            print(f"📁 File saved at: {pdf_output}")
    else:
        print("\n❌ All methods failed. Please try manual conversion.")
