"""Theme system for consistent widget visuals."""

from __future__ import annotations

import os
import sys
from dataclasses import dataclass, field


@dataclass
class WidgetTheme:
    """Centralized theming for consistent visuals."""

    # Status icons
    status_icons: dict[str, str] = field(
        default_factory=lambda: {
            "not_started": "⚪",
            "running": "🟡",
            "completed": "🟢",
            "failed": "🔴",
            "stale": "🟡⏸️",
        }
    )

    # Trendline characters (8 levels)
    bar_chars: str = "▁▂▃▄▅▆▇█"

    # Progress bar characters
    progress_filled: str = "▓"
    progress_empty: str = "░"

    # Trend arrows
    arrows: dict[str, str] = field(
        default_factory=lambda: {
            "up_steep": "↑",
            "up_gradual": "↗",
            "flat": "→",
            "down_gradual": "↘",
            "down_steep": "↓",
        }
    )

    # Threshold colors
    threshold_colors: dict[str, str] = field(
        default_factory=lambda: {
            "good": "green",
            "warn": "yellow",
            "bad": "red",
            "neutral": "cyan",
        }
    )

    @classmethod
    def for_terminal(cls, unicode: bool, emoji: bool) -> WidgetTheme:
        """Create theme based on terminal capabilities."""
        if not unicode:
            # ASCII-only terminals
            return cls(
                bar_chars="#" * 8,
                progress_filled="#",
                progress_empty="-",
                arrows={
                    "up_steep": "^",
                    "up_gradual": "/",
                    "flat": "-",
                    "down_gradual": "\\",
                    "down_steep": "v",
                },
            )
        if not emoji:
            # Unicode but no emoji
            return cls(
                status_icons={
                    "not_started": "○",
                    "running": "◉",
                    "completed": "●",
                    "failed": "✗",
                    "stale": "◎",
                }
            )
        return cls()  # Full unicode + emoji


# Global theme instance
_theme: WidgetTheme | None = None


def get_theme() -> WidgetTheme:
    """Get current global theme."""
    global _theme
    if _theme is None:
        # Auto-detect terminal capabilities
        caps = detect_capabilities()
        _theme = WidgetTheme.for_terminal(unicode=caps["unicode"], emoji=caps["emoji"])
    return _theme


def set_theme(theme: WidgetTheme):
    """Set global theme."""
    global _theme
    _theme = theme


def detect_capabilities() -> dict[str, bool]:
    """Detect terminal capabilities."""
    return {
        "interactive": sys.stdout.isatty(),
        "color": _supports_color(),
        "unicode": _supports_unicode(),
        "emoji": _supports_emoji(),
        "width": os.get_terminal_size().columns if sys.stdout.isatty() else 80,
    }


def _supports_color() -> bool:
    """Check if terminal supports color."""
    if not sys.stdout.isatty():
        return False

    # Check environment variables
    if os.environ.get("NO_COLOR"):
        return False
    if os.environ.get("FORCE_COLOR"):
        return True

    # Check TERM variable
    term = os.environ.get("TERM", "")
    return "color" in term or term in ("xterm", "xterm-256color", "screen")


def _supports_unicode() -> bool:
    """Check if terminal supports unicode."""
    encoding = sys.stdout.encoding or ""
    return encoding.lower() in ("utf-8", "utf8")


def _supports_emoji() -> bool:
    """Check if terminal supports emoji."""
    # Most modern terminals support emoji if they support unicode
    if not _supports_unicode():
        return False

    # Disable emoji in CI environments (conservative)
    ci_vars = ("CI", "GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI")
    if any(os.environ.get(var) for var in ci_vars):
        return False

    return True
