# Supra Theme - Python Example
# This file demonstrates syntax highlighting for Python

from typing import List, Dict, Optional, Union, Any
from dataclasses import dataclass
from enum import Enum
import asyncio
import json
from datetime import datetime

class UserRole(Enum):
    ADMIN = "admin"
    USER = "user"
    MODERATOR = "moderator"

@dataclass
class User:
    id: str
    name: str
    email: str
    age: Optional[int] = None
    role: UserRole = UserRole.USER
    created_at: datetime = None
    
    def __post_init__(self):
        if self.created_at is None:
            self.created_at = datetime.now()

class DatabaseService:
    def __init__(self, api_key: str, url: str, timeout: int = 30):
        self.api_key = api_key
        self.url = url
        self.timeout = timeout
        self.is_connected = False
    
    async def connect(self) -> List[User]:
        """Connect to the database and fetch initial users."""
        try:
            # Simulate async database call
            await asyncio.sleep(0.1)
            users_data = [
                {
                    "id": "1",
                    "name": "John Doe",
                    "email": "john@example.com",
                    "age": 30,
                    "role": "admin"
                },
                {
                    "id": "2", 
                    "name": "Jane Smith",
                    "email": "jane@example.com",
                    "age": 25,
                    "role": "user"
                }
            ]
            
            users = [User(**user_data) for user_data in users_data]
            self.is_connected = True
            print("Connected to database successfully")
            return users
            
        except Exception as e:
            print(f"Database connection failed: {e}")
            raise
    
    async def create_user(self, user_data: Dict[str, Any]) -> User:
        """Create a new user in the database."""
        required_fields = ["name", "email"]
        missing_fields = [field for field in required_fields if field not in user_data]
        
        if missing_fields:
            raise ValueError(f"Missing required fields: {missing_fields}")
        
        # Simulate async database insert
        await asyncio.sleep(0.05)
        
        user = User(
            id=str(len(self.users) + 1),
            name=user_data["name"],
            email=user_data["email"],
            age=user_data.get("age"),
            role=UserRole(user_data.get("role", "user"))
        )
        
        return user
    
    async def find_users_by_role(self, role: UserRole) -> List[User]:
        """Find all users with a specific role."""
        if not self.is_connected:
            raise ConnectionError("Database not connected")
        
        # Simulate async database query
        await asyncio.sleep(0.02)
        
        # This would be a real database query in practice
        return [user for user in self.users if user.role == role]
    
    def to_json(self, user: User) -> str:
        """Convert user object to JSON string."""
        return json.dumps({
            "id": user.id,
            "name": user.name,
            "email": user.email,
            "age": user.age,
            "role": user.role.value,
            "created_at": user.created_at.isoformat()
        }, indent=2)

# Async context manager
class DatabaseConnection:
    def __init__(self, api_key: str, url: str):
        self.api_key = api_key
        self.url = url
        self.service = None
    
    async def __aenter__(self):
        self.service = DatabaseService(self.api_key, self.url)
        await self.service.connect()
        return self.service
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.service:
            self.service.is_connected = False
            print("Database connection closed")

# Main execution
async def main():
    """Main function demonstrating the database service."""
    api_key = "your-api-key-here"
    url = "https://your-project.supabase.co"
    
    async with DatabaseConnection(api_key, url) as db:
        # Create a new user
        new_user_data = {
            "name": "Alice Johnson",
            "email": "alice@example.com",
            "age": 28,
            "role": "moderator"
        }
        
        try:
            user = await db.create_user(new_user_data)
            print(f"Created user: {db.to_json(user)}")
            
            # Find users by role
            admins = await db.find_users_by_role(UserRole.ADMIN)
            print(f"Found {len(admins)} admin users")
            
        except Exception as e:
            print(f"Error: {e}")

# List comprehension and generator expressions
def process_users(users: List[User]) -> Dict[str, List[str]]:
    """Process users and group by role."""
    return {
        role.value: [user.name for user in users if user.role == role]
        for role in UserRole
    }

# Type hints with generics
def filter_users(users: List[User], predicate) -> List[User]:
    """Filter users based on a predicate function."""
    return [user for user in users if predicate(user)]

# Usage example
if __name__ == "__main__":
    # Run the async main function
    asyncio.run(main())
    
    # Example with list comprehension
    sample_users = [
        User("1", "John", "john@example.com", 30, UserRole.ADMIN),
        User("2", "Jane", "jane@example.com", 25, UserRole.USER),
        User("3", "Bob", "bob@example.com", 35, UserRole.MODERATOR)
    ]
    
    grouped = process_users(sample_users)
    print(f"Users grouped by role: {grouped}")
    
    # Filter users older than 30
    older_users = filter_users(sample_users, lambda u: u.age and u.age > 30)
    print(f"Users older than 30: {[u.name for u in older_users]}")
