"""PDF export service using ReportLab."""

from io import BytesIO
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer


def create_pdf(title: str, text: str, metadata: dict = None) -> bytes:
    """
    Create a PDF document from transcription text.

    Args:
        title: Document title
        text: Transcription text content
        metadata: Optional dict with url, duration, created_at, etc.

    Returns:
        PDF file as bytes
    """
    buffer = BytesIO()
    doc = SimpleDocTemplate(
        buffer,
        pagesize=letter,
        rightMargin=inch,
        leftMargin=inch,
        topMargin=inch,
        bottomMargin=inch
    )

    # Get styles
    styles = getSampleStyleSheet()

    # Custom styles
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=18,
        spaceAfter=12,
        textColor='#1e293b'
    )

    meta_style = ParagraphStyle(
        'Metadata',
        parent=styles['Normal'],
        fontSize=10,
        textColor='#64748b',
        spaceAfter=20
    )

    body_style = ParagraphStyle(
        'Body',
        parent=styles['Normal'],
        fontSize=11,
        leading=16,
        spaceAfter=12,
        textColor='#334155'
    )

    # Build content
    story = []

    # Title
    story.append(Paragraph(title, title_style))

    # Metadata
    if metadata:
        meta_parts = []
        if metadata.get('url'):
            meta_parts.append(f"Source: {metadata['url']}")
        if metadata.get('duration'):
            meta_parts.append(f"Duration: {metadata['duration']}")
        if metadata.get('created_at'):
            meta_parts.append(f"Transcribed: {metadata['created_at']}")
        if meta_parts:
            story.append(Paragraph(' | '.join(meta_parts), meta_style))
    else:
        story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}", meta_style))

    story.append(Spacer(1, 0.2 * inch))

    # Transcription text - split into paragraphs
    paragraphs = text.split('\n\n')
    for para in paragraphs:
        if para.strip():
            # Clean text for PDF (escape special characters)
            clean_text = para.strip().replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
            story.append(Paragraph(clean_text, body_style))

    # Build PDF
    doc.build(story)

    # Get bytes
    pdf_bytes = buffer.getvalue()
    buffer.close()

    return pdf_bytes
