from ..renderer.html_generator import get_current_generator


def title(text: str, level: int = 1):
    """Render a title/heading"""
    gen = get_current_generator()
    gen.add_element('title', {'text': text, 'level': level})


def card():
    """Context manager for a card container"""
    class CardContext:
        def __enter__(self):
            gen = get_current_generator()
            gen.start_container('card')
            return self
        
        def __exit__(self, *args):
            gen = get_current_generator()
            gen.end_container()
    
    return CardContext()


def columns(ratios: list = None):
    """Create columns layout and return column contexts"""
    gen = get_current_generator()
    ratios = ratios or [1, 1]
    
    gen.start_container('columns', {'ratios': ratios})
    
    class ColumnContext:
        def __init__(self, index, parent_gen, is_last):
            self.index = index
            self.parent_gen = parent_gen
            self.is_last = is_last
        
        def __enter__(self):
            self.parent_gen.start_container('column', {'index': self.index})
            return self
        
        def __exit__(self, *args):
            self.parent_gen.end_container()
            if self.is_last:
                self.parent_gen.end_container()
    
    num_cols = len(ratios)
    column_contexts = [ColumnContext(i, gen, i == num_cols - 1) for i in range(num_cols)]
    
    if len(column_contexts) == 2:
        return column_contexts[0], column_contexts[1]
    return tuple(column_contexts)


def container():
    """Context manager for a generic container"""
    class ContainerContext:
        def __enter__(self):
            gen = get_current_generator()
            gen.start_container('div')
            return self
        
        def __exit__(self, *args):
            gen = get_current_generator()
            gen.end_container()
    
    return ContainerContext()
