"""
Markdown Renderer

Advanced markdown rendering with syntax highlighting for code blocks.
"""

from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax


def render_markdown(console: Console, markdown_text: str) -> None:
    """
    Render markdown with syntax highlighting.

    Args:
        console: Rich console instance
        markdown_text: Markdown text to render
    """
    md = Markdown(markdown_text, code_theme="monokai")
    console.print(md)


def render_code_block(console: Console, code: str, language: str = "python") -> None:
    """
    Render a code block with syntax highlighting.

    Args:
        console: Rich console instance
        code: Code to render
        language: Programming language for syntax highlighting
    """
    syntax = Syntax(code, language, theme="monokai", line_numbers=True)
    console.print(syntax)


def extract_code_blocks(markdown_text: str) -> list[tuple[str, str]]:
    """
    Extract code blocks from markdown text.

    Args:
        markdown_text: Markdown text

    Returns:
        List of tuples (language, code)
    """
    import re

    # Pattern to match code blocks with optional language
    pattern = r'```(\w+)?\n(.*?)```'
    matches = re.findall(pattern, markdown_text, re.DOTALL)

    code_blocks = []
    for lang, code in matches:
        language = lang if lang else "text"
        code_blocks.append((language, code.strip()))

    return code_blocks
