#!/usr/bin/env python3
"""
Professional Markdown to PDF Converter
Converts Retool Product Analytics Plan to a styled PDF using weasyprint
"""

import markdown2
from weasyprint import HTML, CSS
import os
from pathlib import Path

def convert_markdown_to_pdf(input_file, output_file):
    """Convert markdown file to professional PDF with styling"""
    
    # Read the markdown file
    with open(input_file, 'r', encoding='utf-8') as f:
        markdown_content = f.read()
    
    # Convert markdown to HTML with extras for better formatting
    html_content = markdown2.markdown(
        markdown_content,
        extras=[
            'fenced-code-blocks',  # For code blocks
            'tables',              # For table support
            'header-ids',          # For heading anchors
            'toc',                # Table of contents
            'strike',             # Strikethrough
            'task_list',          # For checkboxes
            'footnotes',          # For footnotes
            'cuddled-lists',      # Better list formatting
            'code-friendly',      # Better code handling
        ]
    )
    
    # Professional CSS styling
    css_styles = """
    @page {
        size: A4;
        margin: 0.75in;
        @top-center {
            content: "Retool Product Analytics Strategy";
            font-family: 'Segoe UI', 'Arial', sans-serif;
            font-size: 10px;
            color: #666;
            margin-bottom: 0.5in;
        }
        @bottom-center {
            content: "Page " counter(page);
            font-family: 'Segoe UI', 'Arial', sans-serif;
            font-size: 10px;
            color: #666;
        }
    }
    
    body {
        font-family: 'Segoe UI', 'Arial', sans-serif;
        line-height: 1.6;
        color: #333;
        margin: 0;
        padding: 0;
        font-size: 11px;
    }
    
    /* Headings */
    h1 {
        color: #2c3e50;
        font-size: 24px;
        font-weight: 700;
        margin: 30px 0 20px 0;
        padding-bottom: 10px;
        border-bottom: 3px solid #3498db;
        page-break-after: avoid;
    }
    
    h2 {
        color: #34495e;
        font-size: 20px;
        font-weight: 600;
        margin: 25px 0 15px 0;
        padding-bottom: 5px;
        border-bottom: 2px solid #ecf0f1;
        page-break-after: avoid;
    }
    
    h3 {
        color: #2c3e50;
        font-size: 16px;
        font-weight: 600;
        margin: 20px 0 12px 0;
        page-break-after: avoid;
    }
    
    h4 {
        color: #34495e;
        font-size: 14px;
        font-weight: 600;
        margin: 15px 0 10px 0;
        page-break-after: avoid;
    }
    
    h5, h6 {
        color: #34495e;
        font-size: 12px;
        font-weight: 600;
        margin: 12px 0 8px 0;
        page-break-after: avoid;
    }
    
    /* Paragraphs */
    p {
        margin: 0 0 12px 0;
        text-align: justify;
    }
    
    /* Lists */
    ul, ol {
        margin: 12px 0;
        padding-left: 20px;
    }
    
    li {
        margin: 5px 0;
    }
    
    /* Code blocks */
    pre {
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 4px;
        padding: 15px;
        margin: 15px 0;
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
        font-size: 10px;
        line-height: 1.4;
        overflow-x: auto;
        page-break-inside: avoid;
    }
    
    code {
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 3px;
        padding: 2px 4px;
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
        font-size: 10px;
        color: #e74c3c;
    }
    
    /* Tables */
    table {
        width: 100%;
        border-collapse: collapse;
        margin: 15px 0;
        font-size: 10px;
        page-break-inside: avoid;
    }
    
    th {
        background-color: #3498db;
        color: white;
        font-weight: 600;
        padding: 10px 8px;
        border: 1px solid #2980b9;
        text-align: left;
    }
    
    td {
        padding: 8px;
        border: 1px solid #bdc3c7;
        vertical-align: top;
    }
    
    tr:nth-child(even) {
        background-color: #f8f9fa;
    }
    
    /* Blockquotes */
    blockquote {
        border-left: 4px solid #3498db;
        margin: 15px 0;
        padding: 10px 20px;
        background-color: #f8f9fa;
        font-style: italic;
        color: #555;
    }
    
    /* Horizontal rule */
    hr {
        border: none;
        border-top: 2px solid #ecf0f1;
        margin: 25px 0;
    }
    
    /* Links */
    a {
        color: #3498db;
        text-decoration: none;
    }
    
    a:hover {
        text-decoration: underline;
    }
    
    /* Task lists / checkboxes */
    .task-list-item {
        list-style: none;
        margin-left: -20px;
    }
    
    .task-list-item input[type="checkbox"] {
        margin-right: 8px;
    }
    
    /* Emphasis */
    strong {
        font-weight: 700;
        color: #2c3e50;
    }
    
    em {
        font-style: italic;
        color: #555;
    }
    
    /* Page breaks */
    .page-break {
        page-break-before: always;
    }
    
    /* Executive summary styling */
    .executive-summary {
        background-color: #f8f9fa;
        border-left: 5px solid #3498db;
        padding: 20px;
        margin: 20px 0;
    }
    
    /* Metric boxes */
    .metric-box {
        background-color: #ecf0f1;
        border-radius: 5px;
        padding: 10px;
        margin: 10px 0;
    }
    
    /* Success criteria checkmarks */
    .success-criteria {
        background-color: #d5f4e6;
        border-left: 4px solid #27ae60;
        padding: 15px;
        margin: 15px 0;
    }
    
    /* Special formatting for checkmarks */
    .checkmark {
        color: #27ae60;
        font-weight: bold;
    }
    """
    
    # Wrap HTML content with proper structure
    full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Retool Product Analytics Strategy</title>
        <style>{css_styles}</style>
    </head>
    <body>
        {html_content}
    </body>
    </html>
    """
    
    # Process the HTML to enhance checkmarks and special formatting
    full_html = full_html.replace('✅', '<span class="checkmark">✅</span>')
    
    # Convert to PDF using weasyprint
    try:
        HTML(string=full_html).write_pdf(output_file)
        return True
    except Exception as e:
        print(f"Error converting to PDF: {e}")
        return False

def main():
    """Main conversion function"""
    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(f"Converting {input_file} to {output_file}...")
    
    if not os.path.exists(input_file):
        print(f"Error: Input file {input_file} not found!")
        return False
    
    success = convert_markdown_to_pdf(input_file, output_file)
    
    if success:
        # Get file size
        file_size = os.path.getsize(output_file)
        file_size_mb = file_size / (1024 * 1024)
        
        print(f"✅ Successfully converted to PDF!")
        print(f"📁 Output file: {output_file}")
        print(f"📊 File size: {file_size:,} bytes ({file_size_mb:.2f} MB)")
        return True
    else:
        print("❌ Conversion failed!")
        return False

if __name__ == "__main__":
    main()