from typing import Tuple
import io
import markdown
from xhtml2pdf import pisa
from config import config

# Get configured logger
logger = config.get_logger(__name__)

def convert_markdown_to_pdf(markdown_content: str, page_title: str) -> Tuple[bytes, str]:
    """
    Convert Markdown content to PDF format.
    
    Args:
        markdown_content: The Markdown content to convert
        page_title: The title of the page for the PDF document
        
    Returns:
        Tuple[bytes, str]: PDF content as bytes and suggested filename
        
    Raises:
        Exception: If PDF conversion fails
    """
    try:
        logger.info(f"Converting markdown to PDF for page: {page_title}")
        
        # Convert Markdown to HTML
        md = markdown.Markdown(extensions=['tables', 'fenced_code', 'toc'])
        html_content = md.convert(markdown_content)
        
        # Create a complete HTML document with basic styling
        html_document = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>{page_title}</title>
            <style>
                body {{
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
                    line-height: 1.6;
                    margin: 40px;
                    color: #333;
                }}
                h1, h2, h3, h4, h5, h6 {{
                    color: #2c3e50;
                    margin-top: 24px;
                    margin-bottom: 16px;
                }}
                h1 {{
                    border-bottom: 2px solid #eaecef;
                    padding-bottom: 10px;
                }}
                code {{
                    background-color: #f6f8fa;
                    padding: 2px 4px;
                    border-radius: 3px;
                    font-family: 'Consolas', 'Monaco', monospace;
                }}
                pre {{
                    background-color: #f6f8fa;
                    padding: 16px;
                    border-radius: 6px;
                    overflow-x: auto;
                    font-family: 'Consolas', 'Monaco', monospace;
                }}
                blockquote {{
                    border-left: 4px solid #dfe2e5;
                    padding-left: 16px;
                    margin-left: 0;
                    color: #6a737d;
                }}
                table {{
                    border-collapse: collapse;
                    width: 100%;
                    margin: 12px 0;
                    table-layout: fixed;
                    word-wrap: break-word;
                    overflow-wrap: break-word;
                    font-size: 10px;
                }}
                th, td {{
                    border: 1px solid #dfe2e5;
                    padding: 4px 6px;
                    text-align: left;
                    word-wrap: break-word;
                    overflow-wrap: break-word;
                    hyphens: auto;
                    font-size: 9px;
                    line-height: 1.2;
                    vertical-align: top;
                }}
                th {{
                    background-color: #f6f8fa;
                    font-weight: bold;
                    font-size: 8px;
                }}
                /* Dynamic column sizing based on content */
                table th:first-child,
                table td:first-child {{
                    width: 40%;
                }}
                table th:nth-child(2),
                table td:nth-child(2) {{
                    width: 15%;
                }}
                table th:nth-child(3),
                table td:nth-child(3) {{
                    width: 45%;
                }}
                /* For tables with more than 3 columns, distribute evenly */
                table th:nth-child(n+4),
                table td:nth-child(n+4) {{
                    width: auto;
                }}
                /* Page margins and body adjustments */
                body {{
                    margin: 20px 15px;
                }}
                ul, ol {{
                    padding-left: 30px;
                }}
                li {{
                    margin: 4px 0;
                }}
            </style>
        </head>
        <body>
            {html_content}
        </body>
        </html>
        """
        
        # Create PDF from HTML
        output = io.BytesIO()
        pisa_status = pisa.CreatePDF(html_document, dest=output)
        
        if pisa_status.err:
            logger.error(f"PDF conversion failed with errors: {pisa_status.err}")
            raise Exception("Failed to generate PDF from markdown content")
        
        pdf_content = output.getvalue()
        output.close()
        
        # Generate filename
        from app import sanitize_filename
        safe_filename = sanitize_filename(page_title)
        filename = f"{safe_filename}.pdf"
        
        logger.info(f"Successfully converted markdown to PDF: {filename}")
        return pdf_content, filename
        
    except Exception as e:
        logger.error(f"Error converting markdown to PDF: {str(e)}")
        raise Exception(f"PDF conversion failed: {str(e)}")
