import os
import re
from dotenv import load_dotenv
from notion_to_md import export_notion_page_to_markdown

# Load environment variables
load_dotenv()

def sanitize_filename(title: str) -> str:
    """
    Sanitize a string to make it safe for use as a filename.
    
    Args:
        title: The original title string
        
    Returns:
        str: A sanitized filename-safe string
    """
    # Replace invalid characters with underscores
    sanitized = re.sub(r'[<>:"/\\|?*]', '_', title)
    # Remove or replace other problematic characters
    sanitized = re.sub(r'[^\w\s\-_.]', '_', sanitized)
    # Replace multiple spaces with single spaces and strip
    sanitized = re.sub(r'\s+', ' ', sanitized).strip()
    # Replace spaces with underscores
    sanitized = sanitized.replace(' ', '_')
    # Limit length to avoid filesystem issues
    if len(sanitized) > 100:
        sanitized = sanitized[:100]
    # Ensure it's not empty
    if not sanitized or sanitized == '_':
        sanitized = 'Untitled'
    
    return sanitized

def test_complete_workflow():
    """Test the complete workflow including filename generation"""
    page_id = '2725bd136a8480a69301d6e70171cdad'
    try:
        print("Testing complete workflow...")
        
        # Get page title and content
        page_title, markdown_content = export_notion_page_to_markdown(page_id)
        print(f"✅ Extracted title: '{page_title}'")
        
        # Generate safe filename
        safe_filename = sanitize_filename(page_title)
        filename = f"{safe_filename}.md"
        print(f"✅ Generated filename: '{filename}'")
        
        # Show what the browser would receive
        print(f"\n📊 Summary:")
        print(f"   Original title: '{page_title}'")
        print(f"   Safe filename: '{filename}'")
        print(f"   Content length: {len(markdown_content)} characters")
        print(f"   Content starts with: '{markdown_content[:50]}...'")
        
        return True
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return False

if __name__ == '__main__':
    test_complete_workflow()
