"""
PDF generation module for saving questionnaires.
"""

import os
import fitz  # PyMuPDF

# Handle imports for both running from src and from parent directory
try:
    from config import PDF_MARGIN, PDF_FONT_SIZE
except ImportError:
    from .config import PDF_MARGIN, PDF_FONT_SIZE


def save_text_as_pdf(text, filename):
    """
    Saves text content as a formatted PDF file using PyMuPDF with full Unicode support.
    
    Args:
        text (str): Text content to save
        filename (str): Output PDF filename
    """
    # Create output directory if it doesn't exist
    output_dir = os.path.dirname(filename)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    
    # Create a new PDF document
    doc = fitz.open()
    
    # Page dimensions (letter size: 8.5 x 11 inches = 612 x 792 points)
    page_width = 612
    page_height = 792
    
    # Create first page
    page = doc.new_page(width=page_width, height=page_height)
    
    # Set up text positioning
    margin = PDF_MARGIN
    x = margin
    y = margin
    max_width = page_width - (2 * margin)
    line_height = PDF_FONT_SIZE * 1.2  # 1.2 line spacing
    
    # Font settings - using built-in font with Unicode support
    fontname = "helv"  # Helvetica
    fontsize = PDF_FONT_SIZE
    
    # Split text into lines
    lines = text.split('\n')
    
    for line in lines:
        # Handle empty lines
        if not line.strip():
            y += line_height
            # Check if we need a new page
            if y + line_height > page_height - margin:
                page = doc.new_page(width=page_width, height=page_height)
                y = margin
            continue
        
        # Word wrap for long lines
        words = line.split()
        current_line = ""
        
        for word in words:
            test_line = current_line + (" " if current_line else "") + word
            # Estimate text width (rough approximation: 0.5 * fontsize per character)
            text_width = len(test_line) * fontsize * 0.5
            
            if text_width <= max_width:
                current_line = test_line
            else:
                # Write current line and start new one
                if current_line:
                    page.insert_text(
                        (x, y),
                        current_line,
                        fontname=fontname,
                        fontsize=fontsize,
                        color=(0, 0, 0)
                    )
                    y += line_height
                    
                    # Check if we need a new page
                    if y + line_height > page_height - margin:
                        page = doc.new_page(width=page_width, height=page_height)
                        y = margin
                
                current_line = word
        
        # Write the last line
        if current_line:
            page.insert_text(
                (x, y),
                current_line,
                fontname=fontname,
                fontsize=fontsize,
                color=(0, 0, 0)
            )
            y += line_height
            
            # Check if we need a new page
            if y + line_height > page_height - margin:
                page = doc.new_page(width=page_width, height=page_height)
                y = margin
    
    # Save the PDF
    doc.save(filename)
    doc.close()
    print(f"PDF saved to: {filename}")
