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_indented_links():
    """Test the indented links functionality with heading demotion."""
    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 has link_to_page blocks
    page_id = "2735bd136a84809cafeee7057d8bf99b"
    
    try:
        logger.info(f"🔄 Converting page with indented links: {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")
        
        # Check for indented content (lines that start with 4 spaces)
        lines = markdown.split('\n')
        indented_lines = [line for line in lines if line.startswith('    ') and line.strip()]
        logger.info(f"📐 Found {len(indented_lines)} indented lines from embedded content")
        
        # Check for demoted headings in embedded content (should have more #'s)
        embedded_headings = [line for line in lines if line.strip().startswith('    #')]
        logger.info(f"📑 Found {len(embedded_headings)} headings in embedded content")
        
        # Show sample of indented content
        if indented_lines:
            logger.info("📋 Sample indented lines:")
            for i, line in enumerate(indented_lines[:5]):
                logger.info(f"  Line {i+1}: {line[:100]}..." if len(line) > 100 else f"  Line {i+1}: {line}")
            
            if len(indented_lines) > 5:
                logger.info(f"  ... and {len(indented_lines) - 5} more indented lines")
        
        # Show sample of embedded headings
        if embedded_headings:
            logger.info("📑 Sample embedded headings:")
            for i, heading in enumerate(embedded_headings[:5]):
                logger.info(f"  Heading {i+1}: {heading.strip()}")
            
            if len(embedded_headings) > 5:
                logger.info(f"  ... and {len(embedded_headings) - 5} more embedded headings")
        
        # Check for table content that's also indented
        indented_table_rows = [line for line in lines if line.startswith('    |') and '---' not in line]
        if indented_table_rows:
            logger.info(f"📊 Found {len(indented_table_rows)} indented table rows")
            
            # Show first indented table row as sample
            if indented_table_rows:
                sample_row = indented_table_rows[0]
                logger.info(f"📋 Sample indented table row: {sample_row[:100]}...")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Error testing indented links: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """Main function to test the indented links functionality."""
    print("=" * 60)
    print("INDENTED LINKS TEST")
    print("=" * 60)
    
    success = test_indented_links()
    
    if success:
        print("\n✅ Indented links test completed successfully!")
        print("Linked page content should now be indented and have demoted headings.")
    else:
        print("\n❌ Indented links test failed - check the logs above")

if __name__ == '__main__':
    main()
