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_final_output():
    """Test and save a sample of the final output to demonstrate all features."""
    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
    page_id = "2735bd136a84809cafeee7057d8bf99b"
    
    try:
        logger.info(f"🔄 Converting page for final output: {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")
        
        # Save a sample of the output to demonstrate the features
        lines = markdown.split('\n')
        
        # Get first 50 lines as a sample
        sample_lines = lines[:50]
        sample_output = '\n'.join(sample_lines)
        
        # Save to file for inspection
        with open('sample_output.md', 'w', encoding='utf-8') as f:
            f.write(sample_output)
            if len(lines) > 50:
                f.write(f'\n\n... and {len(lines) - 50} more lines\n')
                f.write(f'Total document length: {len(markdown)} characters\n')
        
        logger.info("📄 Saved sample output to 'sample_output.md'")
        
        # Show key features in the output
        features_found = []
        
        # Check for embedded content
        indented_lines = [line for line in lines if line.startswith('    ') and line.strip()]
        if indented_lines:
            features_found.append(f"✅ Embedded content: {len(indented_lines)} indented lines")
        
        # Check for demoted headings
        demoted_headings = [line for line in lines if line.startswith('    #')]
        if demoted_headings:
            features_found.append(f"✅ Demoted headings: {len(demoted_headings)} headings")
        
        # Check for tables with <br> tags
        br_count = markdown.count('<br>')
        if br_count > 0:
            features_found.append(f"✅ Table newline fix: {br_count} <br> tags")
        
        # Check for indented tables
        indented_tables = [line for line in lines if line.startswith('    |')]
        if indented_tables:
            features_found.append(f"✅ Indented tables: {len(indented_tables)} table rows")
        
        logger.info("🎯 Features successfully implemented:")
        for feature in features_found:
            logger.info(f"   {feature}")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Error in final output test: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """Main function for final output test."""
    print("=" * 60)
    print("FINAL OUTPUT TEST")
    print("=" * 60)
    
    success = test_final_output()
    
    if success:
        print("\n✅ Final output test completed successfully!")
        print("✨ All features are working:")
        print("   • Link to page embedding with recursion prevention")
        print("   • Table export with proper newline handling")
        print("   • Embedded content indentation and heading demotion")
        print("\nCheck 'sample_output.md' for a sample of the generated markdown.")
    else:
        print("\n❌ Final output test failed - check the logs above")

if __name__ == '__main__':
    main()
