"""Status rendering utilities for terminal applications.

This module provides utility functions for status rendering.
Uses core.ui.design_system for T(), S, C, TagBox, Box, solid, gradient.
"""

import re
import logging
import sys
from typing import List, Optional

from core.ui.design_system import T, solid, solid_fg
from core.io.terminal_state import get_global_width
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .status.navigation_manager import StatusNavigationState

logger = logging.getLogger(__name__)


def _fg(text: str, color: tuple) -> str:
    """Apply foreground color only (no background).

    Args:
        text: Text to colorize
        color: RGB tuple (r, g, b)

    Returns:
        Text with ANSI foreground color codes
    """
    r, g, b = color
    return f"\033[38;2;{r};{g};{b}m{text}\033[39m"


# ============================================================================
# NAVIGATION RENDERING HELPERS
# ============================================================================

def render_selected_widget(text: str, width: int) -> str:
    """Render widget with solid block selection highlight.

    Uses solid block style (▄▀) NOT ASCII brackets, following design system.

    Args:
        text: Widget text to render
        width: Total width for the widget

    Returns:
        Rendered widget with top border, highlighted content, and bottom border
    """
    # Top border using solid blocks
    top = solid_fg("▄" * width, T().primary[0])

    # Content with solid background (primary color background, dark text)
    # Left-pad text with 1 space, right-pad to fit width
    visible_text = text[:width - 4]  # Leave room for spaces and ellipsis
    content = solid(f" {visible_text:<{width - 4}} ", T().primary[0], T().text_dark, width)

    # Bottom border using solid blocks
    bottom = solid_fg("▀" * width, T().primary[0])

    return f"{top}\n{content}\n{bottom}"


def render_mode_indicator(nav_state: Optional['StatusNavigationState']) -> str:
    """Render mode indicator using design system.

    Shows INPUT (dark), NAVIGATE (ai_tag green), or INTERACT (warning orange).

    Args:
        nav_state: StatusNavigationState instance (None = INPUT mode)

    Returns:
        Rendered mode indicator string
    """
    if nav_state is None:
        mode = " INPUT "
        bg, fg = T().dark[0], T().text
    elif nav_state.interaction_active:
        mode = " INTERACT "
        bg, fg = T().warning[0], T().text_dark
    elif nav_state.active:
        mode = " NAVIGATE "
        bg, fg = T().ai_tag, T().text_dark
    else:
        mode = " INPUT "
        bg, fg = T().dark[0], T().text

    return solid(mode, bg, fg, len(mode))


def _bg_line(text: str, bg: tuple, width: int) -> str:
    """Apply background to entire line, preserving any existing foreground colors.

    Args:
        text: Text that may contain ANSI foreground codes
        bg: RGB tuple for background
        width: Total width to pad to

    Returns:
        Text with background applied, preserving fg codes
    """
    r, g, b = bg
    # Set background at start, pad to width, reset at end
    # The \033[K clears to end of line with current bg
    visible_len = len(re.sub(r'\033\[[0-9;]*m', '', text))
    padding = max(0, width - visible_len)
    return f"\033[48;2;{r};{g};{b}m{text}{' ' * padding}\033[0m"


# Platform check for keyboard shortcut display
IS_WINDOWS = sys.platform == "win32"
