import os
from dotenv import load_dotenv
from notion_to_md import export_notion_page_to_markdown
from md_to_pdf import convert_markdown_to_pdf
import logging

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_pdf_formatting():
    """
    Test the PDF formatting issue with the specific Notion page ID provided.
    Page ID: 2725bd13-6a84-8072-916b-c5a1a37c56c3
    """
    # Load environment variables
    load_dotenv()
    
    page_id = "2725bd13-6a84-8072-916b-c5a1a37c56c3"
    
    try:
        logger.info(f"Testing PDF formatting for page: {page_id}")
        
        # Export the page content
        page_title, markdown_content = export_notion_page_to_markdown(page_id)
        logger.info(f"Retrieved markdown content: {len(markdown_content)} characters")
        
        # Convert to PDF
        pdf_content, filename = convert_markdown_to_pdf(markdown_content, page_title)
        logger.info(f"Generated PDF: {filename}")
        
        # Save PDF to file
        with open(filename, 'wb') as f:
            f.write(pdf_content)
        logger.info(f"PDF saved to: {filename}")
        
        # Also save the HTML intermediate step for debugging
        import markdown
        md = markdown.Markdown(extensions=['tables', 'fenced_code', 'toc'])
        html_content = md.convert(markdown_content)
        
        with open("debug_html_output.html", 'w', encoding='utf-8') as f:
            f.write(html_content)
        logger.info("HTML debug output saved to: debug_html_output.html")
        
        # Analyze the HTML for the problematic section
        if "The method:" in html_content:
            method_index = html_content.find("The method:")
            section_start = max(0, method_index - 200)
            section_end = min(len(html_content), method_index + 1000)
            html_section = html_content[section_start:section_end]
            
            logger.info("HTML section around 'The method:':")
            print("\n" + "="*50)
            print("HTML OUTPUT:")
            print("="*50)
            print(html_section)
            print("="*50)
        
        return pdf_content, filename
        
    except Exception as e:
        logger.error(f"Error testing PDF formatting: {str(e)}")
        raise

if __name__ == "__main__":
    test_pdf_formatting()
