"""Startup banner display for session context."""
import logging
import re
from typing import Optional

logger = logging.getLogger(__name__)


def extract_session_context(system_prompt: str) -> Optional[str]:
    """Extract SESSION CONTEXT section from rendered system prompt.

    Args:
        system_prompt: The fully rendered system prompt with <trender> tags processed

    Returns:
        The SESSION CONTEXT section if found, None otherwise
    """
    # Look for the session context section
    pattern = r'SESSION CONTEXT \(loaded at startup\):\s*-+\s*(.*?)\s*-+\s*>'
    match = re.search(pattern, system_prompt, re.DOTALL | re.IGNORECASE)

    if match:
        return match.group(1).strip()

    return None


def format_banner(session_context: str, visual_effects=None) -> str:
    """Format session context as a nice startup banner with gradients.

    Args:
        session_context: The extracted session context text
        visual_effects: Optional VisualEffects instance for gradients

    Returns:
        Formatted banner string
    """
    lines = session_context.split('\n')

    # Build the banner
    banner = []

    # Top border with gradient
    border_line = "=" * 80
    if visual_effects:
        border_line = visual_effects.apply_message_gradient(border_line, "dim_scheme")
    banner.append(border_line)

    # Title with gradient
    title = "KOLLABOR SESSION CONTEXT"
    if visual_effects:
        title = visual_effects.apply_message_gradient(title, "dim_scheme")
    banner.append(title)

    # Bottom title border with gradient
    if visual_effects:
        banner.append(visual_effects.apply_message_gradient("=" * 80, "dim_scheme"))
    else:
        banner.append("=" * 80)

    # Process content lines with subtle gradients
    for line in lines:
        # Skip empty lines at start/end
        if not line.strip():
            continue

        # Apply gradient to content lines
        if visual_effects:
            # Headers (all caps or ending with :) get dim_scheme gradient
            if line.strip().isupper() or line.strip().endswith(':'):
                line = visual_effects.apply_message_gradient(line, "dim_scheme")
            # Content lines get dim_white gradient
            else:
                line = visual_effects.apply_message_gradient(line, "dim_white")

        banner.append(line)

    # Bottom border with gradient
    if visual_effects:
        banner.append(visual_effects.apply_message_gradient("=" * 80, "dim_scheme"))
    else:
        banner.append("=" * 80)

    return '\n'.join(banner)


def display_startup_banner(system_prompt: str, renderer=None) -> None:
    """Display startup banner with session context.

    Args:
        system_prompt: The fully rendered system prompt
        renderer: Optional terminal renderer for styled output
    """
    session_context = extract_session_context(system_prompt)

    if not session_context:
        logger.warning("No SESSION CONTEXT section found in system prompt")
        return

    # Get visual effects from renderer if available
    visual_effects = None
    if renderer and hasattr(renderer, 'visual_effects'):
        visual_effects = renderer.visual_effects

    banner = format_banner(session_context, visual_effects)

    # Display the banner
    if renderer and hasattr(renderer, 'print_system_message'):
        # Use renderer if available for styled output
        renderer.print_system_message(banner)
    else:
        # Fallback to print
        print("\n" + banner + "\n")

    logger.info("Displayed startup banner with session context")
