#!/usr/bin/env python3

import markdown2
import weasyprint
import os
from datetime import datetime

def convert_markdown_to_pdf(markdown_file, output_file):
    """Convert markdown to professional PDF using weasyprint"""
    
    # Read the markdown file
    with open(markdown_file, 'r', encoding='utf-8') as f:
        markdown_content = f.read()
    
    # Convert markdown to HTML with extensions
    html = markdown2.markdown(markdown_content, extras=[
        'fenced-code-blocks',
        'tables',
        'task_list',
        'header-ids',
        'toc',
        'wiki-tables',
        'code-friendly'
    ])
    
    # CSS styles for professional appearance
    css_styles = """
    <style>
        @page {
            size: A4;
            margin: 1in;
            @bottom-center {
                content: counter(page);
                font-family: 'Georgia', serif;
                font-size: 10pt;
                color: #666;
            }
        }
        
        body {
            font-family: 'Georgia', 'Times New Roman', serif;
            line-height: 1.6;
            color: #333;
            max-width: none;
            margin: 0;
            padding: 0;
        }
        
        h1 {
            font-size: 28pt;
            color: #2c3e50;
            margin-top: 0;
            margin-bottom: 20pt;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10pt;
            page-break-after: avoid;
        }
        
        h2 {
            font-size: 22pt;
            color: #34495e;
            margin-top: 30pt;
            margin-bottom: 15pt;
            border-bottom: 2px solid #bdc3c7;
            padding-bottom: 8pt;
            page-break-after: avoid;
        }
        
        h3 {
            font-size: 18pt;
            color: #2980b9;
            margin-top: 25pt;
            margin-bottom: 12pt;
            page-break-after: avoid;
        }
        
        h4 {
            font-size: 16pt;
            color: #8e44ad;
            margin-top: 20pt;
            margin-bottom: 10pt;
            page-break-after: avoid;
        }
        
        h5 {
            font-size: 14pt;
            color: #16a085;
            margin-top: 18pt;
            margin-bottom: 8pt;
            page-break-after: avoid;
        }
        
        h6 {
            font-size: 12pt;
            color: #27ae60;
            margin-top: 16pt;
            margin-bottom: 6pt;
            page-break-after: avoid;
        }
        
        p {
            margin-bottom: 12pt;
            text-align: justify;
        }
        
        ul, ol {
            margin-bottom: 12pt;
            padding-left: 25pt;
        }
        
        li {
            margin-bottom: 6pt;
        }
        
        /* Code blocks */
        pre {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4pt;
            padding: 12pt;
            margin: 12pt 0;
            font-family: 'Monaco', 'Consolas', 'Liberation Mono', monospace;
            font-size: 9pt;
            line-height: 1.4;
            overflow-x: auto;
            page-break-inside: avoid;
        }
        
        code {
            background-color: #f1f2f6;
            padding: 2pt 4pt;
            border-radius: 3pt;
            font-family: 'Monaco', 'Consolas', 'Liberation Mono', monospace;
            font-size: 9pt;
            color: #e74c3c;
        }
        
        /* Tables */
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 15pt 0;
            font-size: 10pt;
            page-break-inside: avoid;
        }
        
        th, td {
            border: 1pt solid #bdc3c7;
            padding: 8pt 10pt;
            text-align: left;
            vertical-align: top;
        }
        
        th {
            background-color: #ecf0f1;
            font-weight: bold;
            color: #2c3e50;
        }
        
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        /* Blockquotes */
        blockquote {
            margin: 15pt 0;
            padding: 10pt 15pt;
            background-color: #ecf0f1;
            border-left: 4pt solid #3498db;
            font-style: italic;
        }
        
        /* HR styling */
        hr {
            border: none;
            height: 2pt;
            background-color: #bdc3c7;
            margin: 25pt 0;
        }
        
        /* Task list styling for checkmarks */
        .task-list-item {
            list-style-type: none;
        }
        
        .task-list-item-checkbox[checked] + span:before {
            content: "✅ ";
            font-size: 12pt;
        }
        
        .task-list-item-checkbox:not([checked]) + span:before {
            content: "☐ ";
            font-size: 12pt;
        }
        
        /* Ensure checkmarks are visible */
        .task-list-item input[type="checkbox"] {
            display: none;
        }
        
        /* Page breaks */
        .page-break {
            page-break-before: always;
        }
        
        /* Executive summary styling */
        .executive-summary {
            background-color: #f8f9fa;
            border: 2pt solid #3498db;
            border-radius: 6pt;
            padding: 15pt;
            margin: 20pt 0;
        }
        
        /* Metric boxes */
        .metric-box {
            background-color: #e8f4f8;
            border-left: 4pt solid #3498db;
            padding: 10pt;
            margin: 10pt 0;
        }
        
        strong {
            color: #2c3e50;
        }
        
        em {
            color: #7f8c8d;
        }
    </style>
    """
    
    # Process checkmarks in HTML
    html = html.replace('☐', '<span style="color: #95a5a6;">☐</span>')
    html = html.replace('✅', '<span style="color: #27ae60; font-size: 12pt;">✅</span>')
    
    # Create complete HTML document
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Retool Product Analytics Strategy</title>
        {css_styles}
    </head>
    <body>
        {html}
        <div style="margin-top: 40pt; padding-top: 20pt; border-top: 1pt solid #bdc3c7; text-align: center; color: #7f8c8d; font-size: 9pt;">
            Generated on {datetime.now().strftime("%B %d, %Y")}
        </div>
    </body>
    </html>
    """
    
    # Convert HTML to PDF
    pdf = weasyprint.HTML(string=html_content)
    pdf.write_pdf(output_file)
    
    return os.path.getsize(output_file)

if __name__ == "__main__":
    input_file = "/Users/igloo/.openclaw/workspace/scratch/retool-product-analytics-plan.md"
    output_file = "/Users/igloo/.openclaw/workspace/scratch/retool-product-analytics-plan.pdf"
    
    print("Converting markdown to PDF...")
    
    try:
        file_size = convert_markdown_to_pdf(input_file, output_file)
        print(f"✅ PDF successfully generated!")
        print(f"📄 Output file: {output_file}")
        print(f"📊 File size: {file_size:,} bytes ({file_size / (1024*1024):.2f} MB)")
        
    except Exception as e:
        print(f"❌ Error during conversion: {e}")
        raise