"""
Display utilities for YBAgent.
Handles rich output rendering in Jupyter Notebooks and standard terminal output.
Features expert-level design with cohesive structure and professional aesthetics.
"""

import sys
import html
from typing import Optional, Literal, List, Any
from enum import Enum

def is_notebook() -> bool:
    """Check if running in a Jupyter Notebook environment."""
    try:
        from IPython import get_ipython
        if 'IPKernelApp' not in get_ipython().config:
            return False
    except (ImportError, AttributeError):
        return False
    return True


class Theme:
    """Professional color theme with semantic naming."""
    # Primary palette - Deep blue tones
    PRIMARY = '#4F46E5'        # Indigo-600
    PRIMARY_LIGHT = '#6366F1'  # Indigo-500
    PRIMARY_DARK = '#4338CA'   # Indigo-700
    
    # Semantic colors
    SUCCESS = '#059669'        # Emerald-600
    SUCCESS_LIGHT = '#10B981'  # Emerald-500
    WARNING = '#D97706'        # Amber-600
    WARNING_LIGHT = '#F59E0B'  # Amber-500
    ERROR = '#DC2626'          # Red-600
    ERROR_LIGHT = '#EF4444'    # Red-500
    INFO = '#2563EB'           # Blue-600
    INFO_LIGHT = '#3B82F6'     # Blue-500
    
    # Neutral palette
    SLATE_50 = '#F8FAFC'
    SLATE_100 = '#F1F5F9'
    SLATE_200 = '#E2E8F0'
    SLATE_300 = '#CBD5E1'
    SLATE_400 = '#94A3B8'
    SLATE_500 = '#64748B'
    SLATE_600 = '#475569'
    SLATE_700 = '#334155'
    SLATE_800 = '#1E293B'
    SLATE_900 = '#0F172A'
    
    # Background system
    BG_PRIMARY = '#FFFFFF'
    BG_SECONDARY = SLATE_50
    BG_TERTIARY = SLATE_100
    BG_DARK = SLATE_900
    BG_DARKER = '#020617'      # Slate-950
    
    # Text system
    TEXT_PRIMARY = SLATE_900
    TEXT_SECONDARY = SLATE_600
    TEXT_TERTIARY = SLATE_500
    TEXT_INVERSE = '#FFFFFF'
    
    # Border system
    BORDER_LIGHT = SLATE_200
    BORDER_DEFAULT = SLATE_300
    BORDER_DARK = SLATE_700


class DisplayManager:
    """
    Expert-level display manager with structured, cohesive design system.
    Implements consistent spacing, typography, and color patterns.
    """
    
    _animations_injected = False
    
    @staticmethod
    def _inject_styles():
        """Inject comprehensive CSS system for consistent styling."""
        if is_notebook() and not DisplayManager._animations_injected:
            from IPython.display import display, HTML
            display(HTML("""
            <style>
                /* Animation System */
                @keyframes ybagent-fadeIn {
                    from { opacity: 0; transform: translateY(8px); }
                    to { opacity: 1; transform: translateY(0); }
                }
                
                @keyframes ybagent-slideIn {
                    from { opacity: 0; transform: translateX(-12px); }
                    to { opacity: 1; transform: translateX(0); }
                }
                
                @keyframes ybagent-pulse {
                    0%, 100% { opacity: 1; transform: scale(1); }
                    50% { opacity: 0.7; transform: scale(0.95); }
                }
                
                /* Base Classes */
                .ybagent-card {
                    animation: ybagent-fadeIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    margin: 12px 0;
                    border-radius: 8px;
                    overflow: hidden;
                }
                
                .ybagent-slide {
                    animation: ybagent-slideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                }
                
                /* Typography */
                .ybagent-monospace {
                    font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', 'Consolas', monospace;
                }
                
                /* Shadows */
                .ybagent-shadow-sm {
                    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
                }
                
                .ybagent-shadow {
                    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
                }
                
                .ybagent-shadow-md {
                    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
                }
                
                .ybagent-shadow-lg {
                    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
                }
            </style>
            """))
            DisplayManager._animations_injected = True
    
    @staticmethod
    def header(text: str, level: int = 1):
        """Display a structured header with proper hierarchy."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            # Size and spacing based on level
            sizes = {1: ('32px', '24px'), 2: ('24px', '20px'), 3: ('20px', '16px')}
            font_size, padding = sizes.get(level, ('18px', '14px'))
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow-md" style="
                background: linear-gradient(135deg, {Theme.PRIMARY} 0%, {Theme.PRIMARY_DARK} 100%);
                padding: {padding};
                margin: 24px 0 16px 0;
            ">
                <h{level} style="
                    margin: 0;
                    color: {Theme.TEXT_INVERSE};
                    font-size: {font_size};
                    font-weight: 700;
                    letter-spacing: -0.02em;
                ">{html.escape(text)}</h{level}>
            </div>
            """
            display(HTML(html_content))
        else:
            prefix = "#" * max(1, min(6, level))
            print(f"{prefix} {text}")

    @staticmethod
    def markdown(text: str):
        """Display markdown text with clean formatting."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_LIGHT};
                padding: 16px 20px;
            ">
                <div style="
                    color: {Theme.TEXT_PRIMARY};
                    font-size: 14px;
                    line-height: 1.7;
                ">{html.escape(text)}</div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(text)

    @staticmethod
    def code(code: str, language: str = "python", title: Optional[str] = None, minimal: bool = False):
        """Display code with professional syntax highlighting structure."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            if minimal:
                html_content = f"""
                <div style="margin: 10px 0;">
                    <pre class="ybagent-monospace" style="
                        margin: 0;
                        padding: 10px;
                        background: transparent;
                        color: {Theme.TEXT_PRIMARY};
                        font-size: 13px;
                        line-height: 1.6;
                        overflow-x: auto;
                        border: none;
                    "><code>{html.escape(code)}</code></pre>
                </div>
                """
                display(HTML(html_content))
                return

            title_bar = ""
            if title:
                title_bar = f"""
                <div style="
                    background: {Theme.SLATE_800};
                    padding: 10px 16px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    border-bottom: 1px solid {Theme.SLATE_700};
                ">
                    <span style="
                        color: {Theme.SLATE_200};
                        font-size: 13px;
                        font-weight: 600;
                    ">{html.escape(title)}</span>
                    <span style="
                        color: {Theme.SLATE_400};
                        font-size: 11px;
                        text-transform: uppercase;
                        letter-spacing: 0.05em;
                    ">{html.escape(language)}</span>
                </div>
                """
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: {Theme.BG_DARKER};
                border: 1px solid {Theme.SLATE_800};
            ">
                {title_bar}
                <pre class="ybagent-monospace" style="
                    margin: 0;
                    padding: 20px;
                    background: {Theme.BG_DARKER};
                    color: {Theme.SLATE_200};
                    font-size: 13px;
                    line-height: 1.6;
                    overflow-x: auto;
                "><code>{html.escape(code)}</code></pre>
            </div>
            """
            display(HTML(html_content))
        else:
            if minimal:
                print(code)
                return

            if title:
                print(f"\n{'─' * 60}")
                print(f"📄 {title} ({language})")
                print('─' * 60)
            print(code)
            print('─' * 60 + '\n')

    @staticmethod
    def step_start(step: int, title: str):
        """Display step with clear visual hierarchy."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-slide ybagent-shadow" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 4px solid {Theme.PRIMARY};
                padding: 16px 20px;
                margin: 20px 0 12px 0;
                display: flex;
                align-items: center;
                gap: 16px;
            ">
                <div style="
                    color: {Theme.TEXT_PRIMARY};
                    font-size: 16px;
                    font-weight: 600;
                    flex: 1;
                ">{html.escape(title)}</div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"\n▸▸▸ {title}")

    @staticmethod
    def observation(content: str, max_length: int = 800):
        """Display observation with structured content display."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            display_content = str(content)
            truncated = len(display_content) > max_length
            if truncated:
                display_content = display_content[:max_length] + '...'
            
            truncated_notice = ""
            if truncated:
                truncated_notice = f'<div style="color: {Theme.SLATE_400}; font-size: 11px; margin-top: 6px; font-style: italic;">Content truncated</div>'
            
            html_content = f"""
            <div class="ybagent-card" style="
                background: {Theme.SLATE_800};
                border-left: 3px solid {Theme.SUCCESS};
                padding: 14px 18px;
            ">
                <div style="
                    display: flex;
                    align-items: flex-start;
                    gap: 12px;
                ">
                    <span style="
                        font-size: 20px;
                        line-height: 1;
                        margin-top: 2px;
                    ">👁️</span>
                    <div style="flex: 1;">
                        <div style="
                            color: {Theme.SUCCESS_LIGHT};
                            font-size: 11px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                            margin-bottom: 8px;
                        ">Observation</div>
                        <pre class="ybagent-monospace" style="
                            margin: 0;
                            padding: 12px;
                            background: {Theme.BG_DARKER};
                            border: 1px solid {Theme.SLATE_700};
                            border-radius: 4px;
                            color: {Theme.SLATE_300};
                            font-size: 12px;
                            line-height: 1.6;
                            white-space: pre-wrap;
                            word-break: break-word;
                            max-height: 300px;
                            overflow-y: auto;
                        ">{html.escape(display_content)}</pre>
                        {truncated_notice}
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"👁️  OBSERVATION: {str(content)[:200]}...")

    @staticmethod
    def success(message: str):
        """Display success with prominent positive styling."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow-md" style="
                background: linear-gradient(135deg, {Theme.SUCCESS} 0%, {Theme.SUCCESS_LIGHT} 100%);
                padding: 16px 20px;
                margin: 16px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                ">
                    <span style="font-size: 24px; line-height: 1;">✓</span>
                    <div style="flex: 1;">
                        <div style="
                            color: rgba(255, 255, 255, 0.9);
                            font-size: 12px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                            margin-bottom: 4px;
                        ">Success</div>
                        <div style="
                            color: {Theme.TEXT_INVERSE};
                            font-size: 14px;
                            line-height: 1.5;
                        ">{html.escape(message)}</div>
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"✓ SUCCESS: {message}")

    @staticmethod
    def warning(message: str):
        """Display warning with attention-grabbing styling."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: linear-gradient(135deg, {Theme.WARNING} 0%, {Theme.WARNING_LIGHT} 100%);
                padding: 16px 20px;
                margin: 16px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                ">
                    <span style="font-size: 24px; line-height: 1;">⚠️</span>
                    <div style="flex: 1;">
                        <div style="
                            color: rgba(255, 255, 255, 0.9);
                            font-size: 12px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                            margin-bottom: 4px;
                        ">Warning</div>
                        <div style="
                            color: {Theme.TEXT_INVERSE};
                            font-size: 14px;
                            line-height: 1.5;
                        ">{html.escape(message)}</div>
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"⚠️  WARNING: {message}")

    @staticmethod
    def error(message: str):
        """Display error with prominent negative styling."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow-md" style="
                background: linear-gradient(135deg, {Theme.ERROR} 0%, {Theme.ERROR_LIGHT} 100%);
                padding: 16px 20px;
                margin: 16px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                ">
                    <span style="font-size: 24px; line-height: 1;">✗</span>
                    <div style="flex: 1;">
                        <div style="
                            color: rgba(255, 255, 255, 0.9);
                            font-size: 12px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                            margin-bottom: 4px;
                        ">Error</div>
                        <div style="
                            color: {Theme.TEXT_INVERSE};
                            font-size: 14px;
                            line-height: 1.5;
                        ">{html.escape(message)}</div>
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"✗ ERROR: {message}")

    @staticmethod
    def info(message: str):
        """Display informational message with neutral styling."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            # Convert message to preserve line breaks
            message_html = html.escape(message).replace('\n', '<br>')
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 3px solid {Theme.INFO};
                padding: 14px 18px;
            ">
                <div style="
                    display: flex;
                    align-items: flex-start;
                    gap: 12px;
                ">
                    <span style="font-size: 20px; line-height: 1; margin-top: 2px;">ℹ️</span>
                    <div style="flex: 1;">
                        <div style="
                            color: {Theme.INFO};
                            font-size: 11px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                            margin-bottom: 6px;
                        ">Info</div>
                        <div style="
                            color: {Theme.TEXT_PRIMARY};
                            font-size: 14px;
                            line-height: 1.7;
                        ">{message_html}</div>
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"ℹ️  INFO: {message}")

    @staticmethod
    def collapsible(title: str, content: str, type: str = "info"):
        """Display collapsible content with expandable details."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            type_config = {
                'info': (Theme.INFO, '📋'),
                'debug': (Theme.WARNING, '🐛'),
                'trace': (Theme.SLATE_500, '🔍')
            }
            color, icon = type_config.get(type, (Theme.INFO, '📋'))
            
            html_content = f"""
            <details class="ybagent-card" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 3px solid {color};
                cursor: pointer;
            ">
                <summary style="
                    padding: 12px 16px;
                    font-size: 13px;
                    font-weight: 600;
                    color: {Theme.TEXT_PRIMARY};
                    user-select: none;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                ">
                    <span>{icon}</span>
                    <span style="flex: 1;">{html.escape(title)}</span>
                    <span style="
                        color: {Theme.TEXT_TERTIARY};
                        font-size: 11px;
                        text-transform: uppercase;
                    ">{type}</span>
                </summary>
                <div style="
                    border-top: 1px solid {Theme.BORDER_LIGHT};
                    background: {Theme.BG_DARKER};
                ">
                    <pre class="ybagent-monospace" style="
                        margin: 0;
                        padding: 16px;
                        color: {Theme.SLATE_300};
                        font-size: 12px;
                        line-height: 1.6;
                        white-space: pre-wrap;
                        max-height: 400px;
                        overflow-y: auto;
                    ">{html.escape(content)}</pre>
                </div>
            </details>
            """
            display(HTML(html_content))
        else:
            print(f"\n{'─' * 60}")
            print(f"{type.upper()}: {title}")
            print('─' * 60)
            preview = content[:400] + "..." if len(content) > 400 else content
            print(preview)
            print('─' * 60 + '\n')

    @staticmethod
    def progress_indicator(message: str):
        """Display progress indicator with animation."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card" style="
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_LIGHT};
                padding: 10px 16px;
                display: flex;
                align-items: center;
                gap: 12px;
            ">
                <div style="
                    width: 6px;
                    height: 6px;
                    background: {Theme.PRIMARY};
                    border-radius: 50%;
                    animation: ybagent-pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
                "></div>
                <span style="
                    color: {Theme.TEXT_SECONDARY};
                    font-size: 13px;
                ">{html.escape(message)}</span>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"⟳ {message}")

    @staticmethod
    def code(code: str, title: str = "Code"):
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 3px solid {Theme.PRIMARY};
                padding: 16px;
                margin: 12px 0;
            ">
                <div style="
                    color: {Theme.PRIMARY};
                    font-size: 12px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: 0.05em;
                    margin-bottom: 8px;
                ">{html.escape(title)}</div>
                <pre class="ybagent-monospace" style="
                    margin: 0;
                    padding: 12px;
                    background: {Theme.BG_TERTIARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 6px;
                    color: {Theme.TEXT_PRIMARY};
                    font-size: 12px;
                    line-height: 1.6;
                    white-space: pre-wrap;
                    word-break: break-word;
                    overflow-x: auto;
                ">{html.escape(str(code))}</pre>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"\n=== {title} ===\n{code}\n")

    @staticmethod
    def markdown(text: str):
        if is_notebook():
            from IPython.display import display, Markdown
            display(Markdown(text))
        else:
            print(text)

    @staticmethod
    def render_html(html_str: str, title: str = "HTML Output", height: int = 420):
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            srcdoc = html.escape(str(html_str)).replace('"', '&quot;')
            html_content = f"""
            <div class=\"ybagent-card ybagent-shadow\" style=\"
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                padding: 12px;
                margin: 12px 0;
            \">
                <div style=\"
                    color: {Theme.SLATE_600};
                    font-size: 12px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: 0.05em;
                    margin-bottom: 8px;
                \">{html.escape(title)}</div>
                <iframe
                    style=\"width: 100%; height: {height}px; border: 1px solid {Theme.BORDER_LIGHT}; border-radius: 6px; background: {Theme.BG_PRIMARY};\"
                    srcdoc=\"{srcdoc}\"
                ></iframe>
            </div>
            """
            display(HTML(html_content))
        else:
            preview = str(html_str)
            print(f"\n[HTML] {title}\n" + (preview[:400] + '...' if len(preview) > 400 else preview))

    @staticmethod
    def step_start(step: int, title: str = "Step"):
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            html_content = f"""
            <div class=\"ybagent-card ybagent-shadow\" style=\"
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 4px solid {Theme.PRIMARY};
                padding: 14px 18px;
                margin: 12px 0;
            \">
                <div style=\"display: flex; align-items: center; gap: 10px;\">
                    <span style=\"font-size: 16px;\">🔄</span>
                    <div style=\"color: {Theme.PRIMARY}; font-size: 13px; font-weight: 700; letter-spacing: -0.02em;\">{html.escape(title)}</div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"\n--- {title} ---")

    @staticmethod
    def thought(text: str):
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            html_content = f"""
            <div class=\"ybagent-card\" style=\"
                background: {Theme.SLATE_800};
                border-left: 3px solid {Theme.WARNING};
                padding: 14px 18px;
            \">
                <div style=\"color: {Theme.WARNING_LIGHT}; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 8px;\">Thought</div>
                <div style=\"color: {Theme.SLATE_200}; font-size: 13px; line-height: 1.6;\">{html.escape(str(text))}</div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"Thought: {text}")

    @staticmethod
    def action(name: str, action_input: str):
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            html_content = f"""
            <div class=\"ybagent-card ybagent-shadow\" style=\"
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_LIGHT};
                padding: 14px 18px;
            \">
                <div style=\"color: {Theme.INFO}; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 8px;\">Action</div>
                <div style=\"color: {Theme.TEXT_PRIMARY}; font-size: 13px; margin-bottom: 6px;\"><strong>{html.escape(name)}</strong></div>
                <pre class=\"ybagent-monospace\" style=\"
                    margin: 0;
                    padding: 12px;
                    background: {Theme.BG_TERTIARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 6px;
                    color: {Theme.TEXT_PRIMARY};
                    font-size: 12px;
                    line-height: 1.6;
                    white-space: pre-wrap;
                    word-break: break-word;
                \">{html.escape(str(action_input))}</pre>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"Action: {name}\nInput: {action_input}")

    @staticmethod
    def collapsible_log(title: str, content: str, level: str = "info"):
        """Display collapsible log content (alias for collapsible method)."""
        DisplayManager.collapsible(title, content, level)

    @staticmethod
    def vector_search(query: str, results: List[Any]):
        """Display vector search results with structured formatting."""
        if not results:
            return

        # Get top result only
        top_result = results[0]
        
        # Try multiple ways to extract content
        if isinstance(top_result, dict):
            content = top_result.get('document') or top_result.get('text') or top_result.get('content') or str(top_result)
        elif hasattr(top_result, 'document'):
            content = top_result.document
        elif hasattr(top_result, 'text'):
            content = top_result.text
        elif hasattr(top_result, 'content'):
            content = top_result.content
        else:
            content = str(top_result)
        
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                padding: 20px;
                margin: 20px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    margin-bottom: 16px;
                    padding-bottom: 16px;
                    border-bottom: 1px solid {Theme.BORDER_LIGHT};
                ">
                    <span style="font-size: 24px;">🔍</span>
                    <div>
                        <div style="
                            color: {Theme.TEXT_TERTIARY};
                            font-size: 11px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                        ">Vector Search</div>
                        <div style="
                            color: {Theme.TEXT_PRIMARY};
                            font-size: 16px;
                            font-weight: 600;
                        ">Query: "{html.escape(query)}"</div>
                    </div>
                </div>
                
                <div style="
                    background: {Theme.BG_PRIMARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 8px;
                    padding: 16px;
                ">
                    <div style="
                        color: {Theme.TEXT_SECONDARY};
                        font-size: 11px;
                        font-weight: 700;
                        text-transform: uppercase;
                        letter-spacing: 0.05em;
                        margin-bottom: 8px;
                    ">Top Result</div>
                    <div style="
                        color: {Theme.TEXT_PRIMARY};
                        font-size: 13px;
                        line-height: 1.6;
                    ">{html.escape(str(content))}</div>
                            letter-spacing: 0.05em;
                            margin-bottom: 6px;
                        ">Info</div>
                        <div style="
                            color: {Theme.TEXT_PRIMARY};
                            font-size: 14px;
                            line-height: 1.7;
                        ">{message_html}</div>
                    </div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"ℹ️  INFO: {message}")

    @staticmethod
    def collapsible(title: str, content: str, type: str = "info"):
        """Display collapsible content with expandable details."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            type_config = {
                'info': (Theme.INFO, '📋'),
                'debug': (Theme.WARNING, '🐛'),
                'trace': (Theme.SLATE_500, '🔍')
            }
            color, icon = type_config.get(type, (Theme.INFO, '📋'))
            
            html_content = f"""
            <details class="ybagent-card" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 3px solid {color};
                cursor: pointer;
            ">
                <summary style="
                    padding: 12px 16px;
                    font-size: 13px;
                    font-weight: 600;
                    color: {Theme.TEXT_PRIMARY};
                    user-select: none;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                ">
                    <span>{icon}</span>
                    <span style="flex: 1;">{html.escape(title)}</span>
                    <span style="
                        color: {Theme.TEXT_TERTIARY};
                        font-size: 11px;
                        text-transform: uppercase;
                    ">{type}</span>
                </summary>
                <div style="
                    border-top: 1px solid {Theme.BORDER_LIGHT};
                    background: {Theme.BG_DARKER};
                ">
                    <pre class="ybagent-monospace" style="
                        margin: 0;
                        padding: 16px;
                        color: {Theme.SLATE_300};
                        font-size: 12px;
                        line-height: 1.6;
                        white-space: pre-wrap;
                        max-height: 400px;
                        overflow-y: auto;
                    ">{html.escape(content)}</pre>
                </div>
            </details>
            """
            display(HTML(html_content))
        else:
            print(f"\n{'─' * 60}")
            print(f"{type.upper()}: {title}")
            print('─' * 60)
            preview = content[:400] + "..." if len(content) > 400 else content
            print(preview)
            print('─' * 60 + '\n')

    @staticmethod
    def progress_indicator(message: str):
        """Display progress indicator with animation."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card" style="
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_LIGHT};
                padding: 10px 16px;
                display: flex;
                align-items: center;
                gap: 12px;
            ">
                <div style="
                    width: 6px;
                    height: 6px;
                    background: {Theme.PRIMARY};
                    border-radius: 50%;
                    animation: ybagent-pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
                "></div>
                <span style="
                    color: {Theme.TEXT_SECONDARY};
                    font-size: 13px;
                ">{html.escape(message)}</span>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"⟳ {message}")

    @staticmethod
    def collapsible_log(title: str, content: str, level: str = "info"):
        """Display collapsible log content (alias for collapsible method)."""
        DisplayManager.collapsible(title, content, level)

    @staticmethod
    def vector_search(query: str, results: List[Any]):
        """Display vector search results with structured formatting."""
        if not results:
            return

        # Get top result only
        top_result = results[0]
        
        # Try multiple ways to extract content
        if isinstance(top_result, dict):
            content = top_result.get('document') or top_result.get('text') or top_result.get('content') or str(top_result)
        elif hasattr(top_result, 'document'):
            content = top_result.document
        elif hasattr(top_result, 'text'):
            content = top_result.text
        elif hasattr(top_result, 'content'):
            content = top_result.content
        else:
            content = str(top_result)
        
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow" style="
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                padding: 20px;
                margin: 20px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    margin-bottom: 16px;
                    padding-bottom: 16px;
                    border-bottom: 1px solid {Theme.BORDER_LIGHT};
                ">
                    <span style="font-size: 24px;">🔍</span>
                    <div>
                        <div style="
                            color: {Theme.TEXT_TERTIARY};
                            font-size: 11px;
                            font-weight: 700;
                            text-transform: uppercase;
                            letter-spacing: 0.05em;
                        ">Vector Search</div>
                        <div style="
                            color: {Theme.TEXT_PRIMARY};
                            font-size: 16px;
                            font-weight: 600;
                        ">Query: "{html.escape(query)}"</div>
                    </div>
                </div>
                
                <div style="
                    background: {Theme.BG_PRIMARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 8px;
                    padding: 16px;
                ">
                    <div style="
                        color: {Theme.TEXT_SECONDARY};
                        font-size: 11px;
                        font-weight: 700;
                        text-transform: uppercase;
                        letter-spacing: 0.05em;
                        margin-bottom: 8px;
                    ">Top Result</div>
                    <div style="
                        color: {Theme.TEXT_PRIMARY};
                        font-size: 13px;
                        line-height: 1.6;
                    ">{html.escape(str(content))}</div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"\n{'═' * 60}")
            print(f"🔍 VECTOR SEARCH: \"{query}\"")
            print(f"{'─' * 60}")
            print(f"TOP RESULT:\n{content}")
            print(f"{'═' * 60}\n")

    @staticmethod
    def collapsible(title: str, content: str, type: str = "info"):
        """Display collapsible content with expandable details."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            type_config = {
                'info': (Theme.INFO, '📋'),
                'debug': (Theme.WARNING, '🐛'),
                'trace': (Theme.SLATE_500, '🔍')
            }
            color, icon = type_config.get(type, (Theme.INFO, '📋'))
            
            html_content = f"""
            <details class="ybagent-card" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 3px solid {color};
                cursor: pointer;
            ">
                <summary style="
                    padding: 12px 16px;
                    font-size: 13px;
                    font-weight: 600;
                    color: {Theme.TEXT_PRIMARY};
                    user-select: none;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                ">
                    <span>{icon}</span>
                    <span style="flex: 1;">{html.escape(title)}</span>
                    <span style="
                        color: {Theme.TEXT_TERTIARY};
                        font-size: 11px;
                        text-transform: uppercase;
                    ">{type}</span>
                </summary>
                <div style="
                    border-top: 1px solid {Theme.BORDER_LIGHT};
                    background: {Theme.BG_DARKER};
                ">
                    <pre class="ybagent-monospace" style="
                        margin: 0;
                        padding: 16px;
                        color: {Theme.SLATE_300};
                        font-size: 12px;
                        line-height: 1.6;
                        white-space: pre-wrap;
                        max-height: 400px;
                        overflow-y: auto;
                    ">{html.escape(content)}</pre>
                </div>
            </details>
            """
            display(HTML(html_content))
        else:
            print(f"\n{'─' * 60}")
            print(f"{type.upper()}: {title}")
            print('─' * 60)
            preview = content[:400] + "..." if len(content) > 400 else content
            print(preview)
            print('─' * 60 + '\n')

    @staticmethod
    def progress_indicator(message: str):
        """Display progress indicator with animation."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            
            html_content = f"""
            <div class="ybagent-card" style="
                background: {Theme.BG_SECONDARY};
                border: 1px solid {Theme.BORDER_LIGHT};
                padding: 10px 16px;
                display: flex;
                align-items: center;
                gap: 12px;
            ">
                <div style="
                    width: 6px;
                    height: 6px;
                    background: {Theme.PRIMARY};
                    border-radius: 50%;
                    animation: ybagent-pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
                "></div>
                <span style="
                    color: {Theme.TEXT_SECONDARY};
                    font-size: 13px;
                ">{html.escape(message)}</span>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"⟳ {message}")

    @staticmethod
    def vector_search_results(query: str, results: List[Any]):
        """Alias for vector_search method for backwards compatibility."""
        DisplayManager.vector_search(query, results)

    @staticmethod
    def llm_response(response: str, title: str = "AI Response", query: str = None):
        """Display LLM response with expert formatting, optionally with the query."""
        if is_notebook():
            from IPython.display import display, HTML
            DisplayManager._inject_styles()
            sanitized_response = str(response).replace("**", "")
            
            # Build query section if provided
            query_section = ""
            if query:
                query_section = f"""
                <div style="
                    background: {Theme.BG_SECONDARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 8px;
                    padding: 16px;
                    margin-bottom: 16px;
                ">
                    <div style="
                        color: {Theme.TEXT_TERTIARY};
                        font-size: 11px;
                        font-weight: 700;
                        text-transform: uppercase;
                        letter-spacing: 0.05em;
                        margin-bottom: 8px;
                    ">Query</div>
                    <div style="
                        color: {Theme.TEXT_PRIMARY};
                        font-size: 14px;
                        line-height: 1.6;
                        white-space: pre-wrap;
                    ">{html.escape(query)}</div>
                </div>
                """
            
            html_content = f"""
            <div class="ybagent-card ybagent-shadow-md" style="
                background: {Theme.BG_PRIMARY};
                border: 1px solid {Theme.BORDER_DEFAULT};
                border-left: 4px solid {Theme.PRIMARY};
                padding: 20px;
                margin: 20px 0;
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    margin-bottom: 16px;
                    padding-bottom: 12px;
                    border-bottom: 1px solid {Theme.BORDER_LIGHT};
                ">
                    <span style="font-size: 24px;">🤖</span>
                    <div style="
                        color: {Theme.PRIMARY};
                        font-size: 16px;
                        font-weight: 700;
                        letter-spacing: -0.025em;
                    ">{html.escape(title)}</div>
                </div>
                
                {query_section}
                
                <div style="
                    background: {Theme.BG_SECONDARY};
                    border: 1px solid {Theme.BORDER_LIGHT};
                    border-radius: 8px;
                    padding: 16px;
                ">
                    <div style="
                        color: {Theme.TEXT_TERTIARY};
                        font-size: 11px;
                        font-weight: 700;
                        text-transform: uppercase;
                        letter-spacing: 0.05em;
                        margin-bottom: 8px;
                    ">Response</div>
                    <div style="
                        color: {Theme.TEXT_PRIMARY};
                        font-size: 14px;
                        line-height: 1.8;
                        white-space: pre-wrap;
                    ">{html.escape(sanitized_response)}</div>
                </div>
            </div>
            """
            display(HTML(html_content))
        else:
            print(f"\n{'═' * 60}")
            print(f"🤖 {title.upper()}")
            print(f"{'═' * 60}")
            if query:
                print(f"Query: {query}")
                print(f"{'─' * 60}")
            print(str(response).replace("**", ""))
            print(f"{'═' * 60}\n")