"""
Terminal Colors - Dark mode theming for the orchestrator CLI.

Provides ANSI color codes and formatting helpers for a Claude Code-like
dark mode interface.
"""

import os
import sys
from enum import Enum
from typing import Optional


class Color(Enum):
    """ANSI color codes for terminal output."""
    # Reset
    RESET = "\033[0m"

    # Regular colors
    BLACK = "\033[30m"
    RED = "\033[31m"
    GREEN = "\033[32m"
    YELLOW = "\033[33m"
    BLUE = "\033[34m"
    MAGENTA = "\033[35m"
    CYAN = "\033[36m"
    WHITE = "\033[37m"

    # Bright/Bold colors
    BRIGHT_BLACK = "\033[90m"
    BRIGHT_RED = "\033[91m"
    BRIGHT_GREEN = "\033[92m"
    BRIGHT_YELLOW = "\033[93m"
    BRIGHT_BLUE = "\033[94m"
    BRIGHT_MAGENTA = "\033[95m"
    BRIGHT_CYAN = "\033[96m"
    BRIGHT_WHITE = "\033[97m"

    # Styles
    BOLD = "\033[1m"
    DIM = "\033[2m"
    ITALIC = "\033[3m"
    UNDERLINE = "\033[4m"

    # Background colors
    BG_BLACK = "\033[40m"
    BG_RED = "\033[41m"
    BG_GREEN = "\033[42m"
    BG_YELLOW = "\033[43m"
    BG_BLUE = "\033[44m"
    BG_MAGENTA = "\033[45m"
    BG_CYAN = "\033[46m"
    BG_WHITE = "\033[47m"


# Check if colors are supported
def colors_supported() -> bool:
    """Check if the terminal supports colors."""
    # Check for NO_COLOR environment variable
    if os.environ.get("NO_COLOR"):
        return False

    # Check if we're in a TTY
    if not hasattr(sys.stdout, "isatty") or not sys.stdout.isatty():
        return False

    # Check TERM environment variable
    term = os.environ.get("TERM", "")
    if term in ("dumb", ""):
        return False

    return True


# Global flag
_COLORS_ENABLED = colors_supported()


def enable_colors(enable: bool = True) -> None:
    """Enable or disable colors globally."""
    global _COLORS_ENABLED
    _COLORS_ENABLED = enable


def c(color: Color) -> str:
    """Get color code if colors are enabled."""
    if _COLORS_ENABLED:
        return color.value
    return ""


def style(text: str, *colors: Color) -> str:
    """Apply color/style to text."""
    if not _COLORS_ENABLED:
        return text

    codes = "".join(color.value for color in colors)
    return f"{codes}{text}{Color.RESET.value}"


class Theme:
    """
    Dark mode theme colors - inspired by Claude Code.

    This defines semantic color mappings for different UI elements.
    """

    # Primary colors
    PRIMARY = Color.BRIGHT_CYAN
    SECONDARY = Color.BRIGHT_MAGENTA
    ACCENT = Color.BRIGHT_YELLOW

    # Status colors
    SUCCESS = Color.BRIGHT_GREEN
    ERROR = Color.BRIGHT_RED
    WARNING = Color.BRIGHT_YELLOW
    INFO = Color.BRIGHT_BLUE

    # Text colors
    TEXT = Color.WHITE
    TEXT_DIM = Color.BRIGHT_BLACK
    TEXT_MUTED = Color.DIM

    # UI elements
    HEADER = Color.BRIGHT_CYAN
    BORDER = Color.BRIGHT_BLACK
    PROMPT = Color.BRIGHT_MAGENTA
    COMMAND = Color.BRIGHT_YELLOW
    AGENT_NAME = Color.BRIGHT_CYAN
    TASK_ID = Color.BRIGHT_BLUE

    # Availability status colors
    AVAILABLE = Color.BRIGHT_GREEN
    BUSY = Color.BRIGHT_YELLOW
    LIMITED = Color.YELLOW
    UNAVAILABLE = Color.BRIGHT_RED
    PAUSED = Color.BRIGHT_BLACK


class Formatter:
    """
    Text formatting helpers for the CLI.
    """

    @staticmethod
    def header(text: str) -> str:
        """Format a header."""
        return style(text, Theme.HEADER, Color.BOLD)

    @staticmethod
    def subheader(text: str) -> str:
        """Format a subheader."""
        return style(text, Theme.SECONDARY)

    @staticmethod
    def success(text: str) -> str:
        """Format success message."""
        return style(f"✓ {text}", Theme.SUCCESS)

    @staticmethod
    def error(text: str) -> str:
        """Format error message."""
        return style(f"✗ {text}", Theme.ERROR)

    @staticmethod
    def warning(text: str) -> str:
        """Format warning message."""
        return style(f"⚠ {text}", Theme.WARNING)

    @staticmethod
    def info(text: str) -> str:
        """Format info message."""
        return style(f"ℹ {text}", Theme.INFO)

    @staticmethod
    def dim(text: str) -> str:
        """Dim text."""
        return style(text, Theme.TEXT_DIM)

    @staticmethod
    def bold(text: str) -> str:
        """Bold text."""
        return style(text, Color.BOLD)

    @staticmethod
    def command(cmd: str) -> str:
        """Format a command name."""
        return style(cmd, Theme.COMMAND, Color.BOLD)

    @staticmethod
    def agent(agent_id: str) -> str:
        """Format an agent name."""
        return style(agent_id, Theme.AGENT_NAME)

    @staticmethod
    def task(task_id: str) -> str:
        """Format a task ID."""
        return style(task_id, Theme.TASK_ID)

    @staticmethod
    def prompt(text: str = "orchestrator") -> str:
        """Format the input prompt."""
        arrow = style("❯", Theme.PROMPT, Color.BOLD)
        name = style(text, Theme.PRIMARY)
        return f"{name} {arrow} "

    @staticmethod
    def divider(char: str = "─", width: int = 60) -> str:
        """Create a horizontal divider."""
        return style(char * width, Theme.BORDER)

    @staticmethod
    def box_top(width: int = 60) -> str:
        """Create box top border."""
        return style("╭" + "─" * (width - 2) + "╮", Theme.BORDER)

    @staticmethod
    def box_bottom(width: int = 60) -> str:
        """Create box bottom border."""
        return style("╰" + "─" * (width - 2) + "╯", Theme.BORDER)

    @staticmethod
    def box_line(text: str, width: int = 60) -> str:
        """Create a line inside a box."""
        border = style("│", Theme.BORDER)
        # Calculate padding
        text_len = len(text.replace("\033[", "").split("m")[-1]) if "\033[" in text else len(text)
        padding = width - text_len - 4
        return f"{border} {text}{' ' * max(0, padding)} {border}"

    @staticmethod
    def availability_color(status: str) -> Color:
        """Get color for availability status."""
        return {
            "available": Theme.AVAILABLE,
            "busy": Theme.BUSY,
            "limited": Theme.LIMITED,
            "rate_limited": Theme.WARNING,
            "exhausted": Theme.UNAVAILABLE,
            "unavailable": Theme.UNAVAILABLE,
            "paused": Theme.PAUSED,
        }.get(status.lower(), Theme.TEXT_DIM)

    @staticmethod
    def status_badge(status: str) -> str:
        """Create a colored status badge."""
        color = Formatter.availability_color(status)
        emoji = {
            "available": "●",
            "busy": "◐",
            "limited": "◔",
            "rate_limited": "◑",
            "exhausted": "○",
            "unavailable": "○",
            "paused": "⏸",
        }.get(status.lower(), "○")
        return style(f"{emoji} {status}", color)

    @staticmethod
    def progress_bar(
        percentage: float,
        width: int = 20,
        show_percentage: bool = True,
    ) -> str:
        """Create a colored progress bar."""
        filled = int(width * percentage / 100)
        empty = width - filled

        # Color based on percentage
        if percentage >= 90:
            bar_color = Theme.ERROR
        elif percentage >= 70:
            bar_color = Theme.WARNING
        else:
            bar_color = Theme.SUCCESS

        bar = style("█" * filled, bar_color) + style("░" * empty, Theme.TEXT_DIM)

        if show_percentage:
            pct = style(f"{percentage:>3.0f}%", bar_color if percentage >= 70 else Theme.TEXT)
            return f"[{bar}] {pct}"
        return f"[{bar}]"


# Convenience aliases
fmt = Formatter
