"""Core status views for the Kollabor CLI application.

V1 (Legacy):
    All views use the agnoster powerline style with lime/cyan color scheme.

V2 (Modern Design System):
    Uses core.ui.design_system for T(), S, C, TagBox, Box, solid, gradient.
    Segmented colored sections matching status_v2 pattern from preview-modern-ui.py.
"""

import logging
from pathlib import Path
from typing import List, Optional, Tuple

from .status_renderer import StatusViewConfig, BlockConfig
from .visual_effects import AgnosterSegment
from .terminal_state import get_global_width

# Modern design system imports
from core.ui.design_system import T, S, C, TagBox, Box, solid, solid_fg, gradient

logger = logging.getLogger(__name__)


# Provider visual configuration using design system colors
# Maps provider type to (icon, color_rgb, label_prefix)
PROVIDER_STYLES = {
    "openai": ("[GPT]", T().success[0], "OpenAI"),  # Lime/green
    "anthropic": ("[CLAUDE]", (100, 149, 237), "Anthropic"),  # Cornflower blue
    "azure_openai": ("[AZURE]", (0, 188, 212), "Azure OpenAI"),  # Cyan
    "local": ("[LOCAL]", (158, 158, 158), "Local"),  # Gray
    "custom": ("[CUSTOM]", (158, 158, 158), "Custom"),  # Gray
}


def get_provider_display(profile) -> Tuple[str, str, str]:
    """
    Get provider display information from profile.

    Args:
        profile: LLMProfile instance

    Returns:
        Tuple of (icon_with_color, provider_label, color_code)
    """
    provider_type = profile.provider if hasattr(profile, 'provider') else "openai"
    style = PROVIDER_STYLES.get(provider_type, PROVIDER_STYLES["openai"])
    icon, color_rgb, label = style
    # Convert RGB to ANSI escape
    r, g, b = color_rgb
    color_code = f"\033[38;2;{r};{g};{b}m"
    return f"{color_code}{icon}{S.RESET}", label, color_code


class CoreStatusViews:
    """Provides agnoster-styled core status views."""

    def __init__(self, llm_service=None, config=None, profile_manager=None, agent_manager=None):
        """Initialize core status views."""
        self.llm_service = llm_service
        self.config = config
        self.profile_manager = profile_manager
        self.agent_manager = agent_manager
        self.status_registry = None  # Set during registration

        # Plugin references for task info (set externally)
        self.tmux_plugin = None  # TmuxPlugin instance
        self.task_manager = None  # Future: task/todo manager
 
    def _get_dir_display(self) -> str:
        """Get formatted directory display."""
        try:
            cwd = Path.cwd()
            home = Path.home()
            if cwd == home:
                return "~"
            elif cwd.is_relative_to(home):
                rel_path = cwd.relative_to(home)
                parts = rel_path.parts
                if len(parts) > 2:
                    return f"~/{'/'.join(parts[-2:])}"
                return f"~/{rel_path}"
            return cwd.name or str(cwd)
        except Exception:
            return "?"

    def _get_profile_name(self) -> str:
        """Get active profile name."""
        if self.profile_manager:
            profile = self.profile_manager.get_active_profile()
            if profile:
                return profile.name
        return "default"

    # Internal skills to hide from status display (user-facing skills should show)
    _HIDDEN_SKILLS = {
        "system_prompt",  # Internal, not a user-facing skill
    }

    def _get_agent_info(self) -> tuple:
        """Get active agent name, all skills, and active skills."""
        agent_name = None
        all_skills = []
        active_skills = set()
        if self.agent_manager:
            agent = self.agent_manager.get_active_agent()
            if agent:
                agent_name = agent.name
                all_skills = [s.name for s in agent.list_skills() if s.name not in self._HIDDEN_SKILLS]
                active_skills = set(agent.active_skills) - self._HIDDEN_SKILLS
        return agent_name, all_skills, active_skills

    def _format_agent_skills_line(self, agent_name: str, all_skills: list, active_skills: set, max_width: int = None, position: str = "only") -> str:
        """Format agent/skills line using status_v2 segmented style.

        Renders as a mini status bar: [agent name] [active skills] [inactive/more]

        Args:
            agent_name: Name of the active agent.
            all_skills: List of all skill names.
            active_skills: Set of active skill names.
            max_width: Maximum width for the bar.
            position: Border position - 'only' (both), 'first' (top only),
                     'middle' (no borders), 'last' (bottom only).

        Returns:
            Formatted status line string.
        """
        # Use global width if not specified
        if max_width is None:
            max_width = get_global_width()

        if not agent_name:
            return ""

        # Sort skills: active first, then inactive
        sorted_skills = sorted(all_skills, key=lambda s: (s not in active_skills, s))

        # Build skill text
        active_list = []
        inactive_list = []
        for skill in sorted_skills:
            if skill in active_skills:
                active_list.append(f"⏵{skill}")
            else:
                inactive_list.append(skill)

        # Calculate segment widths
        seg_width = max_width // 3
        remaining = max_width - (seg_width * 2)

        # Left: agent name
        left_text = f" ⌁ {agent_name}"
        # Middle: active skills (up to 2)
        active_text = " ~ " + " ".join(active_list[:2]) if active_list else " ~"
        # Right: inactive count or more
        if len(inactive_list) > 0:
            right_text = f" # +{len(inactive_list)} skills"
        elif len(active_list) > 2:
            right_text = f" # +{len(active_list) - 2} more"
        else:
            right_text = " #"

        # Define segments using thinking_tag for agent line (orange/gold)
        segments = [
            (T().thinking_tag, T().text_dark, left_text, seg_width),
            (T().ai_tag, T().text_dark, active_text, seg_width),
            (T().dark[0], T().text_dim, right_text, remaining),
        ]

        # Determine which borders to show based on position
        show_top = position in ("only", "first")
        show_bottom = position in ("only", "last")

        # Build agent bar with conditional borders
        lines = []
        if show_top:
            lines.append("".join(solid_fg("▄" * w, bg) for bg, _, _, w in segments))
        lines.append("".join(solid(txt.ljust(w)[:w], bg, fg, w) for bg, fg, txt, w in segments))
        if show_bottom:
            lines.append("".join(solid_fg("▀" * w, bg) for bg, _, _, w in segments))

        return "\n".join(lines)

    def _get_model_info(self) -> tuple:
        """Get model name and endpoint from active profile."""
        model = "unknown"
        endpoint = ""

        # Prefer profile_manager as source of truth (supports env vars and reload)
        if self.profile_manager:
            profile = self.profile_manager.get_active_profile()
            if profile:
                model = profile.get_model() or "unknown"
                api_url = profile.get_endpoint() or ""
                if api_url:
                    try:
                        from urllib.parse import urlparse
                        endpoint = urlparse(api_url).hostname or ""
                    except Exception:
                        pass
                return model, endpoint

        # Fallback to api_service if no profile_manager
        if self.llm_service and hasattr(self.llm_service, "api_service"):
            api_service = self.llm_service.api_service
            model = getattr(api_service, "model", "unknown")
            api_url = getattr(api_service, "api_url", "")
            if api_url:
                try:
                    from urllib.parse import urlparse
                    endpoint = urlparse(api_url).hostname or ""
                except Exception:
                    pass
        return model, endpoint

    def _get_status(self) -> tuple:
        """Get status text and variant."""
        if self.llm_service and self.llm_service.is_processing:
            return "* Working", "light"
        return "* Ready", "normal"

    def _get_stats(self) -> tuple:
        """Get message count and token display."""
        msgs = 0
        tokens = 0
        if self.llm_service and hasattr(self.llm_service, "session_stats"):
            stats = self.llm_service.session_stats
            msgs = stats.get("messages", 0)
            tokens = stats.get("input_tokens", 0) + stats.get("output_tokens", 0)

        if tokens < 1000:
            token_display = f"{tokens}"
        elif tokens < 1000000:
            token_display = f"{tokens/1000:.1f}K"
        else:
            token_display = f"{tokens/1000000:.1f}M"

        return msgs, token_display

    def _get_task_info(self) -> dict:
        """Get task/session info from plugins.

        Returns:
            Dict with keys: current_task, pending_count, tmux_sessions, bg_tasks
        """
        info = {
            "current_task": None,
            "pending_count": 0,
            "tmux_sessions": 0,
            "bg_tasks": 0,
        }

        # Get tmux session count from TmuxPlugin.sessions dict
        if self.tmux_plugin:
            try:
                sessions = getattr(self.tmux_plugin, "sessions", {})
                info["tmux_sessions"] = len(sessions)
            except Exception:
                pass

        # Get task manager info (future: todo/task tracking system)
        if self.task_manager:
            try:
                info["current_task"] = getattr(self.task_manager, "current_task", None)
                info["pending_count"] = getattr(self.task_manager, "pending_count", 0)
            except Exception:
                pass

        return info

    def _format_task_line(self, task_info: dict, max_width: int = None) -> List[str]:
        """Format task info lines using powerline style.

        Args:
            task_info: Dict from _get_task_info()
            max_width: Maximum width for the line.

        Returns:
            List of formatted task lines (may be empty if no task info).
        """
        # Use global width if not specified
        if max_width is None:
            max_width = get_global_width()

        lines = []

        # Only show if there's something to display
        has_content = (
            task_info["current_task"]
            or task_info["pending_count"] > 0
            or task_info["tmux_sessions"] > 0
            or task_info["bg_tasks"] > 0
        )

        if not has_content:
            return lines

        seg = AgnosterSegment()

        # Task icon and current task
        if task_info["current_task"]:
            seg.add_neutral(f":: {task_info['current_task']}", "light")
        elif task_info["pending_count"] > 0:
            seg.add_neutral(f":: {task_info['pending_count']} pending", "light")

        # Tmux sessions
        if task_info["tmux_sessions"] > 0:
            seg.add_cyan(f"{task_info['tmux_sessions']} tmux", "dark")

        # Background tasks
        if task_info["bg_tasks"] > 0:
            seg.add_lime(f"{task_info['bg_tasks']} bg running", "dark")

        rendered = seg.render()
        if rendered.strip():
            lines.append(rendered)

        return lines

    def _overview_content(self) -> List[str]:
        """Agnoster overview: dir | profile | provider | model@endpoint | status | stats.

        If an agent is active, adds a second line showing agent and skills.
        """
        try:
            seg = AgnosterSegment()

            # Directory (lime dark)
            seg.add_lime(self._get_dir_display(), "dark")

            # Profile (cyan dark)
            seg.add_cyan(self._get_profile_name(), "dark")

            # Provider with icon (skip for custom/generic providers)
            provider_display, provider_label, _ = self._get_provider_display()
            if provider_label not in ("Custom", "Local"):
                seg.add_neutral(provider_display, "light")

            # Model @ Endpoint (lime)
            model, endpoint = self._get_model_info()
            model_text = f"{model} @ {endpoint}" if endpoint else model
            seg.add_lime(model_text)

            # Status (cyan)
            status_text, variant = self._get_status()
            seg.add_cyan(status_text, variant)

            # Stats (neutral)
            msgs, token_display = self._get_stats()
            seg.add_neutral(f"{msgs} msg | {token_display} tok", "mid")

            lines = [seg.render()]

            # Add agent/skills line if agent is active (no borders - renderer handles those)
            agent_name, all_skills, active_skills = self._get_agent_info()
            if agent_name:
                agent_line = self._format_agent_skills_line(agent_name, all_skills, active_skills, position="middle")
                if agent_line:
                    # Extend instead of append since line might contain multiple lines
                    lines.extend(agent_line.split("\n"))

            # Add task info line if there are active tasks/sessions
            task_info = self._get_task_info()
            task_lines = self._format_task_line(task_info)
            if task_lines:
                lines.extend(task_lines)

            return lines

        except Exception as e:
            logger.error(f"Overview error: {e}")
            return [f"{S.DIM}Status unavailable{S.RESET}"]

    def _get_provider_display(self) -> tuple:
        """Get provider display information from active profile.

        Returns:
            Tuple of (icon_with_color, provider_label, color_code)
        """
        if self.profile_manager:
            profile = self.profile_manager.get_active_profile()
            if profile and hasattr(profile, 'provider'):
                return get_provider_display(profile)
        # Fallback to OpenAI
        style = PROVIDER_STYLES["openai"]
        return f"{style[1]}{style[0]}{S.RESET}", style[2], style[1]

    def _session_content(self) -> List[str]:
        """Agnoster session: messages | tokens in | tokens out | total."""
        try:
            seg = AgnosterSegment()

            msgs = 0
            tokens_in = 0
            tokens_out = 0
            if self.llm_service and hasattr(self.llm_service, "session_stats"):
                stats = self.llm_service.session_stats
                msgs = stats.get("messages", 0)
                tokens_in = stats.get("input_tokens", 0)
                tokens_out = stats.get("output_tokens", 0)

            seg.add_lime(f"Messages: {msgs}", "dark")
            seg.add_cyan(f"In: {tokens_in}", "dark")
            seg.add_lime(f"Out: {tokens_out}")
            seg.add_cyan(f"Total: {tokens_in + tokens_out}")

            return [seg.render()]

        except Exception as e:
            logger.error(f"Session error: {e}")
            return [f"{S.DIM}Session unavailable{S.RESET}"]

    def _llm_details_content(self) -> List[str]:
        """Agnoster LLM details: status | provider | model | endpoint | temp | max_tokens."""
        try:
            seg = AgnosterSegment()

            status_text, _ = self._get_status()
            model, endpoint = self._get_model_info()
            provider_display, provider_label, _ = self._get_provider_display()

            temp = "?"
            max_tokens = "?"
            if self.llm_service and hasattr(self.llm_service, "api_service"):
                api_service = self.llm_service.api_service
                temp = getattr(api_service, "temperature", "?")
                max_tokens = getattr(api_service, "max_tokens", None) or "None"

            seg.add_lime(status_text, "dark")
            seg.add_neutral(provider_display, "light")
            seg.add_cyan(f"Model: {model}", "dark")
            seg.add_lime(f"@ {endpoint}" if endpoint else "local")
            seg.add_cyan(f"Temp: {temp}")
            seg.add_neutral(f"Max: {max_tokens}", "mid")

            return [seg.render()]

        except Exception as e:
            logger.error(f"LLM details error: {e}")
            return [f"{S.DIM}LLM unavailable{S.RESET}"]

    def _minimal_content(self) -> List[str]:
        """Agnoster minimal: status | provider | model | msgs | tokens."""
        try:
            seg = AgnosterSegment()

            status_text, variant = self._get_status()
            model, _ = self._get_model_info()
            provider_display, _, _ = self._get_provider_display()
            msgs, token_display = self._get_stats()

            seg.add_lime(status_text, "dark")
            seg.add_neutral(provider_display, "light")
            seg.add_cyan(model, "dark")
            seg.add_neutral(f"{msgs} msg | {token_display} tok", "mid")

            return [seg.render()]

        except Exception as e:
            logger.error(f"Minimal error: {e}")
            return [f"{S.DIM}--{S.RESET}"]

    # =========================================================================
    # V2 MODERN DESIGN SYSTEM CONTENT PROVIDERS
    # =========================================================================

    def _overview_content_v2(self) -> List[str]:
        """Modern overview using status_v2 segmented style.

        Format: 3-segment horizontal bar matching status_v2 from preview-modern-ui.py
        Segments: [ai_tag: model/status] [response_bg: profile/dir] [dark: stats]
        Plus agent/skills line if agent is active.

        Position is always "middle" (no borders) since this is preceded by the
        input box (which has position="first") and followed by either the agent
        bar and/or hint bar (which has position="last").

        Returns:
            List of formatted status lines.
        """
        try:
            # Note: Cannot call get_view_count() here - it causes infinite recursion
            # because get_view_count() calls _view_has_content() which calls this provider.
            # The hint bar is added by the renderer, not here.
            # Get data
            model, endpoint = self._get_model_info()
            status_text, _ = self._get_status()
            profile_name = self._get_profile_name()
            dir_display = self._get_dir_display()
            msgs, token_display = self._get_stats()

            # Calculate segment widths using global width
            width = get_global_width()
            seg_width = width // 3
            remaining = width - (seg_width * 2)

            # Build segment content
            # Left: status + model (green ai_tag)
            left_text = f" * {status_text.replace('* ', '')} {model}"
            # Middle: profile + directory (gray response_bg)
            mid_text = f" ~ {profile_name} {dir_display}"
            # Right: stats (dark)
            right_text = f" # {msgs} msg {token_display} tok"

            # Define segments: (bg_color, fg_color, text, width)
            segments = [
                (T().ai_tag, T().text_dark, left_text, seg_width),
                (T().response_bg[0], T().text, mid_text, seg_width),
                (T().dark[0], T().text_dim, right_text, remaining),
            ]

            # Check if agent is active
            agent_name, all_skills, active_skills = self._get_agent_info()
            has_agent = bool(agent_name)

            # Status bar: no borders (input provides top, hint/agent provides bottom)
            lines = []
            lines.append("".join(solid(txt.ljust(w)[:w], bg, fg, w) for bg, fg, txt, w in segments))

            # Add agent/skills bar if agent is active (status_v2 style)
            # Agent bar: no borders (hint bar provides bottom border if it exists)
            if has_agent:
                agent_bar = self._format_agent_skills_line(agent_name, all_skills, active_skills, position="middle")
                if agent_bar:
                    lines.extend(agent_bar.split("\n"))

            return lines

        except Exception as e:
            logger.error(f"Overview v2 error: {e}")
            return [solid_fg("Status unavailable", T().text_dim)]

    def _session_content_v2(self) -> List[str]:
        """Modern session using status_v2 segmented style.

        Shows: messages | tokens in/out | total
        """
        try:
            msgs = 0
            tokens_in = 0
            tokens_out = 0
            if self.llm_service and hasattr(self.llm_service, "session_stats"):
                stats = self.llm_service.session_stats
                msgs = stats.get("messages", 0)
                tokens_in = stats.get("input_tokens", 0)
                tokens_out = stats.get("output_tokens", 0)

            # Calculate segment widths
            width = get_global_width()
            seg_width = width // 3
            remaining = width - (seg_width * 2)

            # Build segment content
            left_text = f" * Messages: {msgs}"
            mid_text = f" ~ In: {tokens_in} Out: {tokens_out}"
            right_text = f" # Total: {tokens_in + tokens_out}"

            # Define segments
            segments = [
                (T().ai_tag, T().text_dark, left_text, seg_width),
                (T().response_bg[0], T().text, mid_text, seg_width),
                (T().dark[0], T().text_dim, right_text, remaining),
            ]

            # Build status bar
            top = "".join(solid_fg("▄" * w, bg) for bg, _, _, w in segments)
            mid_line = "".join(solid(txt.ljust(w)[:w], bg, fg, w) for bg, fg, txt, w in segments)
            bot = "".join(solid_fg("▀" * w, bg) for bg, _, _, w in segments)

            return [top, mid_line, bot]

        except Exception as e:
            logger.error(f"Session v2 error: {e}")
            return [solid_fg("Session unavailable", T().text_dim)]

    def _llm_details_content_v2(self) -> List[str]:
        """Modern LLM details using status_v2 segmented style.

        Shows: status/model | endpoint/temp | max_tokens
        """
        try:
            status_text, _ = self._get_status()
            model, endpoint = self._get_model_info()

            temp = "?"
            max_tokens = "?"
            if self.llm_service and hasattr(self.llm_service, "api_service"):
                api_service = self.llm_service.api_service
                temp = getattr(api_service, "temperature", "?")
                max_tokens = getattr(api_service, "max_tokens", None) or "None"

            # Calculate segment widths
            width = get_global_width()
            seg_width = width // 3
            remaining = width - (seg_width * 2)

            # Build segment content
            left_text = f" * {status_text.replace('* ', '')} {model}"
            mid_text = f" ~ {endpoint if endpoint else 'local'} T:{temp}"
            right_text = f" # Max: {max_tokens}"

            # Define segments
            segments = [
                (T().ai_tag, T().text_dark, left_text, seg_width),
                (T().response_bg[0], T().text, mid_text, seg_width),
                (T().dark[0], T().text_dim, right_text, remaining),
            ]

            # Build status bar
            top = "".join(solid_fg("▄" * w, bg) for bg, _, _, w in segments)
            mid_line = "".join(solid(txt.ljust(w)[:w], bg, fg, w) for bg, fg, txt, w in segments)
            bot = "".join(solid_fg("▀" * w, bg) for bg, _, _, w in segments)

            return [top, mid_line, bot]

        except Exception as e:
            logger.error(f"LLM details v2 error: {e}")
            return [solid_fg("LLM unavailable", T().text_dim)]

    def _minimal_content_v2(self) -> List[str]:
        """Modern minimal using status_v2 segmented style.

        Shows: status/model | profile | stats
        """
        try:
            status_text, _ = self._get_status()
            model, _ = self._get_model_info()
            profile_name = self._get_profile_name()
            msgs, token_display = self._get_stats()

            # Calculate segment widths
            width = get_global_width()
            seg_width = width // 3
            remaining = width - (seg_width * 2)

            # Build segment content
            left_text = f" * {status_text.replace('* ', '')} {model}"
            mid_text = f" ~ {profile_name}"
            right_text = f" # {msgs} msg {token_display} tok"

            # Define segments
            segments = [
                (T().ai_tag, T().text_dark, left_text, seg_width),
                (T().response_bg[0], T().text, mid_text, seg_width),
                (T().dark[0], T().text_dim, right_text, remaining),
            ]

            # Build status bar
            top = "".join(solid_fg("▄" * w, bg) for bg, _, _, w in segments)
            mid_line = "".join(solid(txt.ljust(w)[:w], bg, fg, w) for bg, fg, txt, w in segments)
            bot = "".join(solid_fg("▀" * w, bg) for bg, _, _, w in segments)

            return [top, mid_line, bot]

        except Exception as e:
            logger.error(f"Minimal v2 error: {e}")
            return [solid_fg("--", T().text_dim)]

    # =========================================================================
    # V3 SIMPLE TEXT CONTENT PROVIDERS (matches mockup design)
    # =========================================================================

    def _fg(self, text: str, color: tuple) -> str:
        """Apply foreground color only."""
        r, g, b = color
        return f"\033[38;2;{r};{g};{b}m{text}\033[39m"

    def _overview_content_v3(self) -> List[str]:
        """Simple text-based status content matching mockup design.

        Format: icon text  icon text  icon text (separated by double spaces)
        Icons are colored (lime), values are white, labels are dim.

        Returns:
            List of colored status lines.
        """
        lines = []

        # Colors from theme
        accent = T().ai_tag  # lime green for icons
        text_color = T().text  # white for values
        dim = T().text_dim  # gray for labels

        # Line 1: cwd dir  ⌘ profile  model @ endpoint  * status  msgs | tokens
        dir_display = self._get_dir_display()
        profile_name = self._get_profile_name()
        model, endpoint = self._get_model_info()
        status_text, _ = self._get_status()
        msgs, token_display = self._get_stats()

        # Remove leading * from status text for cleaner look
        status_clean = status_text.replace("* ", "")
        model_text = f"{model} @ {endpoint}" if endpoint else model

        line1_parts = [
            self._fg("cwd", accent) + " " + self._fg(dir_display, text_color),
            self._fg("⌘", accent) + " " + self._fg(profile_name, text_color),
            self._fg(model_text, text_color),
            self._fg("*", accent) + " " + self._fg(status_clean, text_color),
            self._fg(f"{msgs} msg", dim) + self._fg(" | ", dim) + self._fg(f"{token_display} tok", dim),
        ]
        lines.append("  ".join(line1_parts))

        # Line 2: agent and skills (if active)
        agent_name, all_skills, active_skills = self._get_agent_info()
        if agent_name:
            # Build skills display
            active_list = [s for s in all_skills if s in active_skills]
            inactive_list = [s for s in all_skills if s not in active_skills]

            skill_parts = []
            if active_list:
                for skill in active_list[:4]:
                    skill_parts.append(self._fg(skill, text_color))
            else:
                skill_parts.append(self._fg("no-skill", dim))

            extra_count = len(inactive_list) + max(0, len(active_list) - 4)
            if extra_count > 0:
                skill_parts.append(self._fg(f"+{extra_count} skills", dim))

            line2 = self._fg("⌁", accent) + " " + self._fg("using", dim) + " " + self._fg(agent_name, text_color) + "  " + "  ".join(skill_parts)
            lines.append(line2)

        # Line 3: task/tmux/bg info (always show)
        task_info = self._get_task_info()
        parts = []

        # Current task or pending count
        if task_info["current_task"]:
            parts.append(self._fg("∷", accent) + " " + self._fg(task_info['current_task'], text_color))
        else:
            pending = task_info["pending_count"]
            parts.append(self._fg("∷", accent) + " " + self._fg(f"{pending} pending", dim if pending == 0 else text_color))

        # Tmux sessions
        tmux_count = task_info["tmux_sessions"]
        parts.append(self._fg(f"{tmux_count} tmux", dim if tmux_count == 0 else text_color))

        # Background tasks
        bg_count = task_info["bg_tasks"]
        parts.append(self._fg(f"{bg_count} bg", dim if bg_count == 0 else text_color))

        lines.append("  ".join(parts))

        return lines

    def register_all_views_v3(self, status_registry) -> None:
        """Register v3 modern status views using simple text format.

        Uses plain text content that the renderer wraps with design system styling.
        """
        # Store registry reference for position calculations
        self.status_registry = status_registry
        try:
            # View 1: Overview v3 (priority 1100 - highest)
            status_registry.register_status_view("core", StatusViewConfig(
                name="Overview",
                plugin_source="core",
                priority=1100,
                blocks=[BlockConfig(
                    width_fraction=1.0,
                    content_provider=self._overview_content_v3,
                    title="Main",
                    priority=100,
                )],
            ))

            logger.info("Registered v3 modern status views")

        except Exception as e:
            logger.error(f"Failed to register v3 modern status views: {e}")

    def register_all_views_v2(self, status_registry) -> None:
        """Register all v2 modern status views alongside v1 views.

        Uses TagBox pattern with segmented colors from core.ui.design_system.
        """
        # Store registry reference for position calculations
        self.status_registry = status_registry
        try:
            # View 1: Overview v2 (priority 1099 - just below v1)
            status_registry.register_status_view("core", StatusViewConfig(
                name="Overview",
                plugin_source="core",
                priority=1099,
                blocks=[BlockConfig(
                    width_fraction=1.0,
                    content_provider=self._overview_content_v2,
                    title="Main",
                    priority=100,
                )],
            ))

            # View 2: Session v2 (priority 999)
            #status_registry.register_status_view("core", StatusViewConfig(
            #    name="Session v2",
            #    plugin_source="core",
            #    priority=999,
            #    blocks=[BlockConfig(
            #        width_fraction=1.0,
            #        content_provider=self._session_content_v2,
            #        title="Session",
            #        priority=100,
            #    )],
            #))

            # View 3: LLM Details v2 (priority 899)
            #status_registry.register_status_view("core", StatusViewConfig(
            #    name="LLM Details v2",
            #    plugin_source="core",
            #    priority=899,
            #    blocks=[BlockConfig(
            #        width_fraction=1.0,
            #        content_provider=self._llm_details_content_v2,
            #        title="LLM",
            #        priority=100,
            #    )],
            #))

            ## View 4: Minimal v2 (priority 599)
            #status_registry.register_status_view("core", StatusViewConfig(
            #    name="Minimal v2",
            #    plugin_source="core",
            #    priority=599,
            #    blocks=[BlockConfig(
            #        width_fraction=1.0,
            #        content_provider=self._minimal_content_v2,
            #        title="Minimal",
            #        priority=100,
            #    )],
            #))

            logger.info("Registered 4 v2 modern status views")

        except Exception as e:
            logger.error(f"Failed to register v2 modern status views: {e}")
