#!/usr/bin/env python3
"""
Generate ebook PDF directly from Markdown using Python libraries
No Pandoc required - uses markdown and reportlab
"""

import os
import re
from pathlib import Path

try:
    from reportlab.lib.pagesizes import letter, A4
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
    from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
    REPORTLAB_AVAILABLE = True
except ImportError:
    REPORTLAB_AVAILABLE = False

try:
    import markdown
    MARKDOWN_AVAILABLE = True
except ImportError:
    MARKDOWN_AVAILABLE = False

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 strip_markdown_simple(text):
    """Simple markdown stripping for plain text."""
    # Remove YAML front matter
    if text.startswith("---"):
        end = text.find("---", 3)
        if end != -1:
            text = text[end + 3:].strip()
    
    # Remove code blocks
    text = re.sub(r'```[\s\S]*?```', '', text)
    text = re.sub(r'`([^`]+)`', r'\1', text)
    
    # Remove images
    text = re.sub(r'!\[([^\]]*)\]\([^\)]+\)', r'\1', text)
    
    # Remove links
    text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
    
    # Remove bold/italic
    text = re.sub(r'\*\*([^\*]+)\*\*', r'\1', text)
    text = re.sub(r'(?<!\*)\*([^\*]+)\*(?!\*)', r'\1', text)
    text = re.sub(r'__(.+?)__', r'\1', text)
    text = re.sub(r'(?<!_)_([^_]+)_(?!_)', r'\1', text)
    
    # Remove headings markers but keep text
    text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)
    
    # Remove blockquotes
    text = re.sub(r'^>\s+', '', text, flags=re.MULTILINE)
    
    # Remove horizontal rules
    text = re.sub(r'^---+$', '', text, flags=re.MULTILINE)
    
    # Remove list markers
    text = re.sub(r'^\s*[-*+]\s+', '', text, flags=re.MULTILINE)
    text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE)
    
    # Clean up whitespace
    text = re.sub(r'\n{3,}', '\n\n', text)
    
    return text.strip()

def create_pdf_with_reportlab():
    """Create PDF using reportlab."""
    print("📚 Generating ebook PDF with ReportLab...")
    print("")
    
    OUTPUT_DIR.mkdir(exist_ok=True)
    output_path = OUTPUT_DIR / "silence-isnt-distance-ebook.pdf"
    
    # Create PDF document
    doc = SimpleDocTemplate(
        str(output_path),
        pagesize=letter,
        rightMargin=1*inch,
        leftMargin=1*inch,
        topMargin=0.75*inch,
        bottomMargin=0.75*inch
    )
    
    # Build content
    story = []
    styles = getSampleStyleSheet()
    
    # Custom styles
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=24,
        textColor='black',
        spaceAfter=30,
        alignment=TA_CENTER,
        fontName='Helvetica-Bold'
    )
    
    chapter_style = ParagraphStyle(
        'CustomChapter',
        parent=styles['Heading1'],
        fontSize=20,
        textColor='black',
        spaceAfter=20,
        spaceBefore=30,
        alignment=TA_LEFT,
        fontName='Helvetica-Bold'
    )
    
    heading2_style = ParagraphStyle(
        'CustomHeading2',
        parent=styles['Heading2'],
        fontSize=16,
        textColor='black',
        spaceAfter=12,
        spaceBefore=18,
        fontName='Helvetica-Bold'
    )
    
    body_style = ParagraphStyle(
        'CustomBody',
        parent=styles['Normal'],
        fontSize=11,
        leading=16,
        alignment=TA_JUSTIFY,
        fontName='Times-Roman'
    )
    
    # Process files
    for filename in sorted(FILE_ORDER.keys(), key=lambda x: FILE_ORDER.get(x, 0)):
        filepath = EXPORT_READY_DIR / filename
        if not filepath.exists():
            continue
        
        print(f"Processing {filename}...")
        
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Strip markdown
        text = strip_markdown_simple(content)
        
        # Split into paragraphs
        paragraphs = text.split('\n\n')
        
        # Add chapter title
        if paragraphs:
            first_line = paragraphs[0].strip()
            if first_line and len(first_line) < 100:  # Likely a title
                story.append(Paragraph(first_line, chapter_style))
                story.append(Spacer(1, 0.2*inch))
                paragraphs = paragraphs[1:]
        
        # Add content
        for para in paragraphs:
            para = para.strip()
            if not para:
                story.append(Spacer(1, 0.1*inch))
                continue
            
            # Check if it's a heading (all caps or short line)
            if para.isupper() and len(para) < 80:
                story.append(Paragraph(para, heading2_style))
            else:
                # Escape HTML entities
                para = para.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
                story.append(Paragraph(para, body_style))
                story.append(Spacer(1, 0.1*inch))
        
        # Page break between chapters
        story.append(PageBreak())
    
    # Build PDF
    print("")
    print("🔄 Building PDF...")
    doc.build(story)
    
    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
    
    return False

def main():
    """Main function."""
    print("📖 Ebook PDF Generator (Direct)")
    print("=" * 50)
    print("")
    
    if not REPORTLAB_AVAILABLE:
        print("❌ ReportLab not installed!")
        print("")
        print("💡 Install with:")
        print("   pip install reportlab")
        print("")
        print("   Then run this script again.")
        return
    
    print("✅ ReportLab found")
    print("")
    
    success = create_pdf_with_reportlab()
    
    if success:
        print("")
        print("✨ PDF generation complete!")
        print("")
        print("📦 File location: export/silence-isnt-distance-ebook.pdf")
    else:
        print("")
        print("❌ PDF generation failed")

if __name__ == "__main__":
    main()

