"""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 condensed startup banner.

    Hides irrelevant sections (those marked with ✗) and only shows
    relevant/detected sections (marked with ✓).

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

    Returns:
        Formatted banner string (condensed, relevant info only)
    """
    lines = session_context.split('\n')

    # Parse into sections and filter out irrelevant ones
    relevant_parts = []
    current_section = []
    current_header = None
    skip_section = False

    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue

        # Detect section headers (all caps ending with :)
        if stripped.endswith(':') and stripped[:-1].replace(' ', '').isupper():
            # Save previous section if it was relevant
            if current_section and not skip_section:
                relevant_parts.extend(current_section)
            # Start new section
            current_header = stripped
            current_section = []
            skip_section = False
            continue

        # Check if this section should be skipped (contains ✗ indicator)
        if '✗' in stripped or 'Not a ' in stripped or 'No ' in stripped and 'found' in stripped:
            skip_section = True
            continue

        # Skip header-like lines and irrelevant markers
        if stripped.isupper():
            continue

        # Add relevant content
        if not skip_section:
            # Clean up the line - remove leading indicators
            clean_line = stripped.lstrip('✓').strip()
            if clean_line:
                current_section.append(clean_line)

    # Don't forget last section
    if current_section and not skip_section:
        relevant_parts.extend(current_section)

    # Filter to project-relevant info only (skip basic system info)
    skip_patterns = [
        'detected', 'consider', 'active',
        'darwin', 'linux', 'arm64', 'x86', 'amd64',  # OS/arch
        '/bin/', '/usr/bin', 'zsh', 'bash', 'fish',  # shells
        '.local', 'hostname', '@',  # hostname stuff
        'whoami', 'uname',
        'none', 'unknown', 'n/a',
    ]

    key_info = []
    for part in relevant_parts:
        part_lower = part.lower()
        # Skip basic system info
        if any(skip in part_lower for skip in skip_patterns):
            continue
        # Extract key details (value after colon)
        if ':' in part:
            value = part.split(':', 1)[1].strip()
            if value and value.lower() not in ['none', 'unknown', '0']:
                key_info.append(value)
        else:
            key_info.append(part)

    # Dedupe and limit
    seen = set()
    unique_info = []
    for info in key_info:
        info_lower = info.lower()
        # Skip if too short, duplicate, or matches skip patterns
        if (info and len(info) > 2 and info not in seen and
            not any(skip in info_lower for skip in skip_patterns)):
            seen.add(info)
            unique_info.append(info)

    if not unique_info:
        return ""  # Nothing relevant to show

    # Format as two-line banner
    # Line 1: First item (usually working directory)
    # Line 2: Remaining items joined with |
    prefix = "[Session]"
    line1 = unique_info[0] if unique_info else ""
    line2 = " | ".join(unique_info[1:5]) if len(unique_info) > 1 else ""

    if visual_effects:
        prefix = visual_effects.apply_message_gradient(prefix, "dim_scheme")
        line1 = visual_effects.apply_message_gradient(line1, "dim_white")
        if line2:
            line2 = visual_effects.apply_message_gradient(line2, "dim_white")

    if line2:
        return f"{prefix} {line1}\n          {line2}"
    else:
        return f"{prefix} {line1}"


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.debug("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)

    # Don't display if nothing relevant
    if not banner:
        logger.debug("No relevant session info to display")
        return

    # Display the banner
    if renderer and hasattr(renderer, 'print_system_message'):
        renderer.print_system_message(banner)
    else:
        print(banner)

    logger.debug("Displayed condensed session banner")
