import os
import logging
from dotenv import load_dotenv
from notion_to_md import NotionToMarkdown

# Load environment variables
load_dotenv()

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_table_fix():
    """Test the table fix by converting the problematic page."""
    notion_token = os.getenv('NOTION_TOKEN')
    if not notion_token:
        logger.error("NOTION_TOKEN environment variable is not set!")
        return False
    
    # Initialize converter
    converter = NotionToMarkdown(notion_token)
    
    # The page ID provided by the user that had table issues
    page_id = "2735bd136a84809cafeee7057d8bf99b"
    
    try:
        logger.info(f"🔄 Converting page with tables: {page_id}")
        
        title, markdown = converter.get_page_content_as_markdown(page_id)
        
        logger.info(f"✅ Successfully converted page: {title}")
        logger.info(f"📏 Generated markdown length: {len(markdown)} characters")
        
        # Look for table structures in the output
        table_count = markdown.count('| --- |')
        logger.info(f"📋 Found {table_count} table separators (indicating {table_count} tables)")
        
        # Check if there are proper table structures
        table_rows = [line for line in markdown.split('\n') if line.strip().startswith('|') and line.strip().endswith('|')]
        logger.info(f"📊 Found {len(table_rows)} table rows")
        
        # Show a sample of the table content (first few table rows)
        if table_rows:
            logger.info("📋 Sample table rows:")
            for i, row in enumerate(table_rows[:5]):  # Show first 5 table rows
                logger.info(f"  Row {i+1}: {row[:100]}..." if len(row) > 100 else f"  Row {i+1}: {row}")
            
            if len(table_rows) > 5:
                logger.info(f"  ... and {len(table_rows) - 5} more rows")
        
        # Check for <br> tags (our fix for newlines)
        br_count = markdown.count('<br>')
        if br_count > 0:
            logger.info(f"🔧 Found {br_count} <br> tags (newlines properly converted)")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Error testing table fix: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """Main function to test the table fix."""
    print("=" * 60)
    print("TABLE FIX TEST")
    print("=" * 60)
    
    success = test_table_fix()
    
    if success:
        print("\n✅ Table fix test completed successfully!")
        print("Tables should now properly handle multi-line content with <br> tags.")
    else:
        print("\n❌ Table fix test failed - check the logs above")

if __name__ == '__main__':
    main()
