#!/usr/bin/env python3
"""
PDF Documentation Generator for Quiz Platform
Converts Markdown documentation to professional PDF format
"""

import os
import sys
from pathlib import Path
import markdown
from weasyprint import HTML, CSS
from datetime import datetime

# Configuration
DOCS_DIR = Path(__file__).parent
OUTPUT_DIR = DOCS_DIR / "pdf"
CSS_TEMPLATE = """
@page {
    size: A4;
    margin: 2cm;
    @top-center {
        content: "Quiz Platform Documentation";
        font-size: 10pt;
        color: #666;
    }
    @bottom-center {
        content: "Page " counter(page) " of " counter(pages);
        font-size: 10pt;
        color: #666;
    }
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    color: #333;
    font-size: 11pt;
}

h1 {
    color: #2c3e50;
    border-bottom: 3px solid #3498db;
    padding-bottom: 10px;
    page-break-before: always;
}

h2 {
    color: #34495e;
    border-bottom: 2px solid #ecf0f1;
    padding-bottom: 5px;
    margin-top: 30px;
}

h3 {
    color: #2c3e50;
    margin-top: 25px;
}

code {
    background-color: #f8f9fa;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    font-size: 10pt;
}

pre {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 5px;
    padding: 15px;
    overflow-x: auto;
    font-family: 'Courier New', monospace;
    font-size: 9pt;
    line-height: 1.4;
}

blockquote {
    border-left: 4px solid #3498db;
    margin: 20px 0;
    padding-left: 20px;
    color: #555;
    font-style: italic;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
}

th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
    font-weight: bold;
}

.toc {
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 5px;
    padding: 20px;
    margin: 20px 0;
}

.toc h2 {
    margin-top: 0;
    color: #495057;
}

.toc ul {
    list-style-type: none;
    padding-left: 0;
}

.toc li {
    margin: 5px 0;
    padding-left: 20px;
}

.cover-page {
    text-align: center;
    padding-top: 200px;
}

.cover-title {
    font-size: 36pt;
    color: #2c3e50;
    margin-bottom: 20px;
}

.cover-subtitle {
    font-size: 18pt;
    color: #7f8c8d;
    margin-bottom: 40px;
}

.cover-date {
    font-size: 12pt;
    color: #95a5a6;
}

.highlight {
    background-color: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 4px;
    padding: 10px;
    margin: 15px 0;
}

.warning {
    background-color: #f8d7da;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    padding: 10px;
    margin: 15px 0;
}

.info {
    background-color: #d1ecf1;
    border: 1px solid #bee5eb;
    border-radius: 4px;
    padding: 10px;
    margin: 15px 0;
}
"""

def create_cover_page(title, subtitle=""):
    """Create a professional cover page"""
    current_date = datetime.now().strftime("%B %Y")
    
    cover_html = f"""
    <div class="cover-page">
        <h1 class="cover-title">{title}</h1>
        <p class="cover-subtitle">{subtitle}</p>
        <div style="margin-top: 100px;">
            <img src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0iIzM0OThkYiIvPgogIDx0ZXh0IHg9IjUwIiB5PSI1NSIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjI0IiBmaWxsPSJ3aGl0ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSI+UT8vdGV4dD4KPC9zdmc+" alt="Quiz Platform Logo" style="width: 100px; height: 100px;">
        </div>
        <p class="cover-date">Generated: {current_date}</p>
        <div style="position: absolute; bottom: 50px; left: 50%; transform: translateX(-50%);">
            <p style="color: #7f8c8d; font-size: 10pt;">
                Advanced Quiz & Poll Platform<br>
                Professional Documentation Suite
            </p>
        </div>
    </div>
    """
    return cover_html

def markdown_to_html(markdown_file):
    """Convert markdown file to HTML with extensions"""
    with open(markdown_file, 'r', encoding='utf-8') as f:
        markdown_content = f.read()
    
    # Configure markdown extensions
    md = markdown.Markdown(extensions=[
        'codehilite',
        'tables',
        'toc',
        'fenced_code',
        'attr_list'
    ])
    
    html_content = md.convert(markdown_content)
    return html_content

def generate_pdf(markdown_file, output_file, title, subtitle=""):
    """Generate PDF from markdown file"""
    print(f"Converting {markdown_file} to {output_file}...")
    
    # Convert markdown to HTML
    html_content = markdown_to_html(markdown_file)
    
    # Create cover page
    cover_page = create_cover_page(title, subtitle)
    
    # Combine cover page and content
    full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>{title}</title>
    </head>
    <body>
        {cover_page}
        <div style="page-break-before: always;"></div>
        {html_content}
    </body>
    </html>
    """
    
    # Generate PDF
    html_doc = HTML(string=full_html)
    css_doc = CSS(string=CSS_TEMPLATE)
    
    html_doc.write_pdf(output_file, stylesheets=[css_doc])
    print(f"✅ Generated: {output_file}")

def main():
    """Main function to generate all PDF documentation"""
    # Create output directory
    OUTPUT_DIR.mkdir(exist_ok=True)
    
    # Documentation files to convert
    docs_to_convert = [
        {
            'file': DOCS_DIR.parent / 'README.md',
            'output': 'README.pdf',
            'title': 'Quiz Platform',
            'subtitle': 'Installation & Quick Start Guide'
        },
        {
            'file': DOCS_DIR / 'DEVELOPER_GUIDE.md',
            'output': 'DEVELOPER_GUIDE.pdf',
            'title': 'Developer Guide',
            'subtitle': 'Technical Documentation for Developers'
        },
        {
            'file': DOCS_DIR / 'SALES_DOCUMENTATION.md',
            'output': 'SALES_DOCUMENTATION.pdf',
            'title': 'Sales Documentation',
            'subtitle': 'Business Guide & Sales Materials'
        },
        {
            'file': DOCS_DIR / 'ADMIN_GUIDE.md',
            'output': 'ADMIN_GUIDE.pdf',
            'title': 'Administrator Guide',
            'subtitle': 'System Administration & Management'
        },
        {
            'file': DOCS_DIR / 'USER_MANUAL.md',
            'output': 'USER_MANUAL.pdf',
            'title': 'User Manual',
            'subtitle': 'Complete User Guide & Tutorial'
        }
    ]
    
    print("🚀 Starting PDF generation...")
    print("=" * 50)
    
    # Generate individual PDFs
    for doc in docs_to_convert:
        if doc['file'].exists():
            output_path = OUTPUT_DIR / doc['output']
            generate_pdf(doc['file'], output_path, doc['title'], doc['subtitle'])
        else:
            print(f"❌ File not found: {doc['file']}")
    
    # Generate combined documentation
    print("\n📚 Generating combined documentation...")
    generate_combined_pdf(docs_to_convert)
    
    print("\n" + "=" * 50)
    print("✅ PDF generation completed!")
    print(f"📁 Output directory: {OUTPUT_DIR}")
    print("\nGenerated files:")
    for pdf_file in OUTPUT_DIR.glob("*.pdf"):
        file_size = pdf_file.stat().st_size / 1024  # KB
        print(f"  • {pdf_file.name} ({file_size:.1f} KB)")

def generate_combined_pdf(docs_to_convert):
    """Generate a single combined PDF with all documentation"""
    combined_html = ""
    
    # Add cover page for combined documentation
    cover_page = create_cover_page(
        "Quiz Platform Documentation Suite",
        "Complete Documentation Package"
    )
    combined_html += cover_page
    
    # Add table of contents
    toc_html = """
    <div style="page-break-before: always;" class="toc">
        <h2>📋 Table of Contents</h2>
        <ul>
            <li><a href="#readme">1. Installation & Quick Start Guide</a></li>
            <li><a href="#developer">2. Developer Guide</a></li>
            <li><a href="#sales">3. Sales Documentation</a></li>
            <li><a href="#admin">4. Administrator Guide</a></li>
            <li><a href="#user">5. User Manual</a></li>
        </ul>
    </div>
    """
    combined_html += toc_html
    
    # Add each document
    section_ids = ['readme', 'developer', 'sales', 'admin', 'user']
    
    for i, doc in enumerate(docs_to_convert):
        if doc['file'].exists():
            html_content = markdown_to_html(doc['file'])
            section_html = f"""
            <div style="page-break-before: always;" id="{section_ids[i]}">
                <h1>{doc['title']}</h1>
                <p style="color: #7f8c8d; font-style: italic; margin-bottom: 30px;">{doc['subtitle']}</p>
                {html_content}
            </div>
            """
            combined_html += section_html
    
    # Create full HTML document
    full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Quiz Platform - Complete Documentation</title>
    </head>
    <body>
        {combined_html}
    </body>
    </html>
    """
    
    # Generate combined PDF
    output_file = OUTPUT_DIR / "COMPLETE_DOCUMENTATION.pdf"
    html_doc = HTML(string=full_html)
    css_doc = CSS(string=CSS_TEMPLATE)
    
    html_doc.write_pdf(output_file, stylesheets=[css_doc])
    print(f"✅ Generated combined documentation: {output_file}")

if __name__ == "__main__":
    try:
        main()
    except ImportError as e:
        print("❌ Missing required packages. Please install:")
        print("pip install markdown weasyprint")
        print(f"Error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"❌ Error generating PDFs: {e}")
        sys.exit(1)