import os
from dotenv import load_dotenv
from notion_to_md import export_notion_page_to_markdown
import logging

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_list_formatting():
    """
    Test the list 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 list formatting for page: {page_id}")
        
        # Export the page content
        page_title, markdown_content = export_notion_page_to_markdown(page_id)
        
        logger.info(f"Successfully retrieved page: {page_title}")
        logger.info(f"Content length: {len(markdown_content)} characters")
        
        # Save the output to a file for inspection
        output_filename = "test_list_formatting_output.md"
        with open(output_filename, 'w', encoding='utf-8') as f:
            f.write(markdown_content)
        
        logger.info(f"Output saved to: {output_filename}")
        
        # Analyze the problematic section
        logger.info("\n=== ANALYZING LIST FORMATTING ===")
        
        # Look for the specific problematic section mentioned in the task
        if "The method:" in markdown_content:
            method_index = markdown_content.find("The method:")
            # Extract a portion around this section for analysis
            section_start = max(0, method_index - 100)
            section_end = min(len(markdown_content), method_index + 2000)
            problematic_section = markdown_content[section_start:section_end]
            
            logger.info("Found 'The method:' section:")
            print("\n" + "="*50)
            print("PROBLEMATIC SECTION:")
            print("="*50)
            print(problematic_section)
            print("="*50)
            
            # Check if the section contains proper list formatting
            lines = problematic_section.split('\n')
            list_items = [line for line in lines if line.strip().startswith(('a.', 'b.', 'c.', 'd.', 'e.', 'f.', 'g.', 'h.', 'i.', 'j.', '1.', '2.', '3.'))]
            
            if len(list_items) > 0:
                logger.info(f"Found {len(list_items)} properly formatted list items")
                for item in list_items[:5]:  # Show first 5 items
                    logger.info(f"  - {item.strip()[:100]}...")
            else:
                logger.warning("No properly formatted list items found in the problematic section!")
                # Look for items that should be list items but aren't formatted properly
                potential_items = []
                for line in lines:
                    if any(line.strip().startswith(prefix) for prefix in ['a.', 'b.', 'c.', 'd.', 'e.', 'f.', 'g.', 'h.', 'i.', 'j.']):
                        potential_items.append(line.strip())
                
                if potential_items:
                    logger.info(f"Found {len(potential_items)} potential list items mixed in text:")
                    for item in potential_items[:3]:
                        logger.info(f"  - {item[:100]}...")
        else:
            logger.warning("Could not find 'The method:' section in the document")
        
        return markdown_content
        
    except Exception as e:
        logger.error(f"Error testing list formatting: {str(e)}")
        raise

if __name__ == "__main__":
    test_list_formatting()
