#!/usr/bin/env python3
"""
Generate ebook-optimized PDF from Markdown files
Uses reportlab as fallback if Pandoc/XeLaTeX not available
"""

import os
import subprocess
import sys
from pathlib import Path

EXPORT_READY_DIR = Path("export-ready")
OUTPUT_DIR = Path("export")

# File order mapping
FILE_ORDER = {
    "00-cover.md": 0,
    "01-title-page.md": 1,
    "02-dedication.md": 2,
    "02a-content-considerations.md": 2.5,
    "03-preface.md": 3,
    "04-how-to-use-this-book.md": 4,
    "05-introduction.md": 5,
    "06-chapter-01-overloaded-mind.md": 6,
    "07-chapter-02-emotional-architecture.md": 7,
    "08-chapter-03-mirror-misunderstanding.md": 8,
    "09-chapter-04-science-of-withdrawal.md": 9,
    "10-chapter-05-shutdown-triggers.md": 10,
    "11-chapter-06-survival-mode-love.md": 11,
    "12-chapter-07-overfunctioning.md": 12,
    "13-chapter-08-projection-mirror.md": 13,
    "14-chapter-09-burnout-breakdown-dissociation.md": 14,
    "15-chapter-10-loving-someone-who-retreats.md": 15,
    "16-chapter-11-what-people-get-wrong.md": 16,
    "17-chapter-12-repair-reconnection.md": 17,
    "18-chapter-13-emotional-bandwidth.md": 18,
    "19-chapter-14-healing-survival-patterns.md": 19,
    "20-chapter-15-coming-home-to-silence.md": 20,
    "21-epilogue.md": 21,
    "22-acknowledgements.md": 22,
    "23-about-the-author.md": 23,
    "24-back-of-book-summary.md": 24,
    "25-bibliography.md": 25,
    "25a-glossary.md": 25.5,
}

def check_pandoc():
    """Check if Pandoc is installed."""
    try:
        result = subprocess.run(['pandoc', '--version'], 
                              capture_output=True, text=True, timeout=5)
        return result.returncode == 0
    except:
        return False

def check_pdf_engine():
    """Check for available PDF engines."""
    engines = []
    
    # Check XeLaTeX
    try:
        result = subprocess.run(['xelatex', '--version'], 
                              capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            engines.append('xelatex')
    except:
        pass
    
    # Check WeasyPrint
    try:
        result = subprocess.run(['weasyprint', '--version'], 
                              capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            engines.append('weasyprint')
    except:
        pass
    
    return engines

def generate_pdf_with_pandoc():
    """Generate PDF using Pandoc."""
    print("📚 Generating ebook PDF with Pandoc...")
    print("")
    
    OUTPUT_DIR.mkdir(exist_ok=True)
    
    # Get all markdown files in order
    md_files = []
    for filename in sorted(FILE_ORDER.keys(), key=lambda x: FILE_ORDER.get(x, 0)):
        filepath = EXPORT_READY_DIR / filename
        if filepath.exists():
            md_files.append(str(filepath))
    
    if not md_files:
        print("❌ No markdown files found!")
        return False
    
    print(f"📄 Found {len(md_files)} files to process")
    print("")
    
    # Check for PDF engines
    engines = check_pdf_engine()
    
    if not engines:
        print("⚠️  No PDF engine found (XeLaTeX or WeasyPrint)")
        print("   Attempting basic PDF generation...")
        pdf_engine = None
    else:
        pdf_engine = engines[0]
        print(f"✅ Using PDF engine: {pdf_engine}")
        print("")
    
    # Build Pandoc command
    output_path = OUTPUT_DIR / "silence-isnt-distance-ebook.pdf"
    
    cmd = [
        'pandoc',
        *md_files,
        '--toc',
        '--toc-depth=2',
        '--metadata', 'title:Silence Isn\'t Distance',
        '--metadata', 'author:Cody "Q" Rice-Velasquez',
        '--metadata', 'subtitle:The Inner World of People Who Feel Deeply, Think Too Much, and Shut Down to Cope',
    ]
    
    # Add PDF engine if available
    if pdf_engine:
        cmd.extend(['--pdf-engine', pdf_engine])
    
    # Ebook-optimized settings
    cmd.extend([
        '--variable', 'geometry:margin=1in',
        '--variable', 'fontsize=11pt',
        '--variable', 'linestretch=1.5',
        '--variable', 'mainfont:Georgia',
        '-o', str(output_path)
    ])
    
    print("🔄 Running Pandoc...")
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
        
        if result.returncode == 0:
            if output_path.exists():
                size_mb = output_path.stat().st_size / (1024 * 1024)
                print(f"✅ PDF created: {output_path}")
                print(f"   Size: {size_mb:.2f} MB")
                return True
            else:
                print("❌ PDF file not created")
                return False
        else:
            print("❌ Pandoc error:")
            print(result.stderr)
            return False
            
    except subprocess.TimeoutExpired:
        print("❌ PDF generation timed out")
        return False
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

def generate_pdf_fallback():
    """Fallback PDF generation using HTML to PDF conversion."""
    print("📚 Attempting fallback PDF generation...")
    print("")
    
    # First, generate HTML
    html_path = OUTPUT_DIR / "silence-isnt-distance-temp.html"
    
    md_files = []
    for filename in sorted(FILE_ORDER.keys(), key=lambda x: FILE_ORDER.get(x, 0)):
        filepath = EXPORT_READY_DIR / filename
        if filepath.exists():
            md_files.append(str(filepath))
    
    cmd = [
        'pandoc',
        *md_files,
        '--toc',
        '--toc-depth=2',
        '--standalone',
        '--css', 'pandoc.css',  # Basic styling
        '-o', str(html_path)
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        if result.returncode == 0 and html_path.exists():
            print("✅ HTML generated, converting to PDF...")
            # Try to convert HTML to PDF using weasyprint
            pdf_path = OUTPUT_DIR / "silence-isnt-distance-ebook.pdf"
            weasyprint_cmd = ['weasyprint', str(html_path), str(pdf_path)]
            result = subprocess.run(weasyprint_cmd, capture_output=True, text=True, timeout=120)
            if result.returncode == 0 and pdf_path.exists():
                size_mb = pdf_path.stat().st_size / (1024 * 1024)
                print(f"✅ PDF created: {pdf_path}")
                print(f"   Size: {size_mb:.2f} MB")
                html_path.unlink()  # Clean up temp HTML
                return True
    except:
        pass
    
    return False

def main():
    """Main function."""
    print("📖 Ebook PDF Generator")
    print("=" * 50)
    print("")
    
    # Check Pandoc
    if not check_pandoc():
        print("❌ Pandoc is not installed!")
        print("   Please install Pandoc from: https://pandoc.org/installing.html")
        return
    
    print("✅ Pandoc found")
    print("")
    
    # Try primary method
    success = generate_pdf_with_pandoc()
    
    # Try fallback if primary failed
    if not success:
        print("")
        print("🔄 Trying fallback method...")
        success = generate_pdf_fallback()
    
    if success:
        print("")
        print("✨ PDF generation complete!")
        print("")
        print("📦 File location: export/silence-isnt-distance-ebook.pdf")
    else:
        print("")
        print("❌ PDF generation failed")
        print("")
        print("💡 Options:")
        print("   1. Install XeLaTeX (MiKTeX or TeX Live)")
        print("   2. Install WeasyPrint: pip install weasyprint")
        print("   3. Use the HTML export and convert manually")

if __name__ == "__main__":
    main()

