"""
Theme System - Color schemes for TUI

Provides comprehensive theming system with:
- 62 color properties matching OpenCode
- 7+ built-in themes (tokyonight, everforest, catppuccin, gruvbox, nord, etc.)
- JSON-based theme format
- Light/dark mode support
- Theme preview and switching

Examples:
    # Load theme
    manager = ThemeManager()
    theme = manager.get_theme("tokyonight")

    # Apply colors
    print(theme.primary("Important text"))
    print(theme.secondary("Secondary text"))

    # List available themes
    themes = manager.list_themes()

    # Preview theme
    manager.preview("everforest")
"""

from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Optional
import json


class ThemeType(Enum):
    """Theme type (light or dark)"""
    DARK = "dark"
    LIGHT = "light"


@dataclass
class Theme:
    """
    Complete theme definition with 62 color properties

    Matches OpenCode's theme system for 100% compatibility.
    All colors are hex strings (#RRGGBB).
    """
    name: str
    display_name: str
    type: ThemeType
    description: str = ""

    # Base colors (4)
    background: str = "#1a1b26"
    foreground: str = "#c0caf5"
    cursor: str = "#c0caf5"
    selection: str = "#33467c"

    # ANSI colors (16)
    black: str = "#15161e"
    red: str = "#f7768e"
    green: str = "#9ece6a"
    yellow: str = "#e0af68"
    blue: str = "#7aa2f7"
    magenta: str = "#bb9af7"
    cyan: str = "#7dcfff"
    white: str = "#a9b1d6"
    bright_black: str = "#414868"
    bright_red: str = "#f7768e"
    bright_green: str = "#9ece6a"
    bright_yellow: str = "#e0af68"
    bright_blue: str = "#7aa2f7"
    bright_magenta: str = "#bb9af7"
    bright_cyan: str = "#7dcfff"
    bright_white: str = "#c0caf5"

    # Semantic colors (12)
    primary: str = "#7aa2f7"
    secondary: str = "#9ece6a"
    accent: str = "#bb9af7"
    info: str = "#7dcfff"
    success: str = "#9ece6a"
    warning: str = "#e0af68"
    error: str = "#f7768e"
    muted: str = "#565f89"
    border: str = "#292e42"
    highlight: str = "#33467c"
    link: str = "#7dcfff"
    code: str = "#bb9af7"

    # UI element colors (30)
    # Status bar
    status_bar_bg: str = "#16161e"
    status_bar_fg: str = "#a9b1d6"
    status_bar_active_bg: str = "#1f2335"
    status_bar_active_fg: str = "#c0caf5"

    # Input
    input_bg: str = "#1f2335"
    input_fg: str = "#c0caf5"
    input_border: str = "#292e42"
    input_focus_border: str = "#7aa2f7"

    # Button
    button_bg: str = "#7aa2f7"
    button_fg: str = "#1a1b26"
    button_hover_bg: str = "#89b4fa"
    button_hover_fg: str = "#1a1b26"

    # Dialog
    dialog_bg: str = "#1f2335"
    dialog_fg: str = "#c0caf5"
    dialog_border: str = "#292e42"
    dialog_shadow: str = "#00000080"

    # Menu
    menu_bg: str = "#1f2335"
    menu_fg: str = "#c0caf5"
    menu_selected_bg: str = "#33467c"
    menu_selected_fg: str = "#c0caf5"
    menu_separator: str = "#292e42"

    # Scrollbar
    scrollbar_bg: str = "#1f2335"
    scrollbar_thumb: str = "#414868"
    scrollbar_thumb_hover: str = "#565f89"

    # Sidebar
    sidebar_bg: str = "#16161e"
    sidebar_fg: str = "#a9b1d6"
    sidebar_border: str = "#292e42"

    # Command palette
    palette_bg: str = "#1f2335"
    palette_fg: str = "#c0caf5"
    palette_match: str = "#7aa2f7"
    palette_selected_bg: str = "#33467c"

    def to_dict(self) -> dict:
        """Convert theme to dictionary"""
        return {
            "name": self.name,
            "display_name": self.display_name,
            "type": self.type.value,
            "description": self.description,
            "colors": {
                # Base
                "background": self.background,
                "foreground": self.foreground,
                "cursor": self.cursor,
                "selection": self.selection,
                # ANSI
                "black": self.black,
                "red": self.red,
                "green": self.green,
                "yellow": self.yellow,
                "blue": self.blue,
                "magenta": self.magenta,
                "cyan": self.cyan,
                "white": self.white,
                "bright_black": self.bright_black,
                "bright_red": self.bright_red,
                "bright_green": self.bright_green,
                "bright_yellow": self.bright_yellow,
                "bright_blue": self.bright_blue,
                "bright_magenta": self.bright_magenta,
                "bright_cyan": self.bright_cyan,
                "bright_white": self.bright_white,
                # Semantic
                "primary": self.primary,
                "secondary": self.secondary,
                "accent": self.accent,
                "info": self.info,
                "success": self.success,
                "warning": self.warning,
                "error": self.error,
                "muted": self.muted,
                "border": self.border,
                "highlight": self.highlight,
                "link": self.link,
                "code": self.code,
                # UI
                "status_bar_bg": self.status_bar_bg,
                "status_bar_fg": self.status_bar_fg,
                "input_bg": self.input_bg,
                "input_fg": self.input_fg,
                "dialog_bg": self.dialog_bg,
                "menu_bg": self.menu_bg,
                # ... all other UI colors
            }
        }

    @classmethod
    def from_dict(cls, data: dict) -> "Theme":
        """Create theme from dictionary"""
        colors = data.get("colors", {})
        return cls(
            name=data["name"],
            display_name=data["display_name"],
            type=ThemeType(data.get("type", "dark")),
            description=data.get("description", ""),
            **colors
        )

    @classmethod
    def from_json(cls, json_path: Path) -> "Theme":
        """Load theme from JSON file"""
        with open(json_path) as f:
            data = json.load(f)
        return cls.from_dict(data)


# Built-in themes

TOKYONIGHT_THEME = Theme(
    name="tokyonight",
    display_name="Tokyo Night",
    type=ThemeType.DARK,
    description="A clean, dark theme inspired by Tokyo's night lights",
    # Base colors
    background="#1a1b26",
    foreground="#c0caf5",
    cursor="#c0caf5",
    selection="#33467c",
    # ANSI colors
    black="#15161e",
    red="#f7768e",
    green="#9ece6a",
    yellow="#e0af68",
    blue="#7aa2f7",
    magenta="#bb9af7",
    cyan="#7dcfff",
    white="#a9b1d6",
    bright_black="#414868",
    bright_red="#f7768e",
    bright_green="#9ece6a",
    bright_yellow="#e0af68",
    bright_blue="#7aa2f7",
    bright_magenta="#bb9af7",
    bright_cyan="#7dcfff",
    bright_white="#c0caf5",
    # Semantic colors
    primary="#7aa2f7",
    secondary="#9ece6a",
    accent="#bb9af7",
    info="#7dcfff",
    success="#9ece6a",
    warning="#e0af68",
    error="#f7768e",
    muted="#565f89",
    border="#292e42",
    highlight="#33467c",
    link="#7dcfff",
    code="#bb9af7",
    # UI element colors
    status_bar_bg="#16161e",
    status_bar_fg="#a9b1d6",
    status_bar_active_bg="#1f2335",
    status_bar_active_fg="#c0caf5",
    input_bg="#1f2335",
    input_fg="#c0caf5",
    input_border="#292e42",
    input_focus_border="#7aa2f7",
    button_bg="#7aa2f7",
    button_fg="#1a1b26",
    button_hover_bg="#89b4fa",
    button_hover_fg="#1a1b26",
    dialog_bg="#1f2335",
    dialog_fg="#c0caf5",
    dialog_border="#292e42",
    dialog_shadow="#00000080",
    menu_bg="#1f2335",
    menu_fg="#c0caf5",
    menu_selected_bg="#33467c",
    menu_selected_fg="#c0caf5",
    menu_separator="#292e42",
    scrollbar_bg="#1f2335",
    scrollbar_thumb="#414868",
    scrollbar_thumb_hover="#565f89",
    sidebar_bg="#16161e",
    sidebar_fg="#a9b1d6",
    sidebar_border="#292e42",
    palette_bg="#1f2335",
    palette_fg="#c0caf5",
    palette_match="#7aa2f7",
    palette_selected_bg="#33467c",
)

EVERFOREST_THEME = Theme(
    name="everforest",
    display_name="Everforest",
    type=ThemeType.DARK,
    description="A comfortable green forest theme for eyes",
    background="#2d353b",
    foreground="#d3c6aa",
    cursor="#d3c6aa",
    selection="#503946",
    black="#374247",
    red="#e67e80",
    green="#a7c080",
    yellow="#dbbc7f",
    blue="#7fbbb3",
    magenta="#d699b6",
    cyan="#83c092",
    white="#d3c6aa",
    bright_black="#414b50",
    bright_red="#e67e80",
    bright_green="#a7c080",
    bright_yellow="#dbbc7f",
    bright_blue="#7fbbb3",
    bright_magenta="#d699b6",
    bright_cyan="#83c092",
    bright_white="#d3c6aa",
    primary="#a7c080",
    secondary="#7fbbb3",
    accent="#d699b6",
    info="#83c092",
    success="#a7c080",
    warning="#dbbc7f",
    error="#e67e80",
    muted="#859289",
    border="#404c51",
    highlight="#503946",
    link="#83c092",
    code="#d699b6",
)

CATPPUCCIN_THEME = Theme(
    name="catppuccin",
    display_name="Catppuccin Mocha",
    type=ThemeType.DARK,
    description="Soothing pastel theme for the high-spirited",
    background="#1e1e2e",
    foreground="#cdd6f4",
    cursor="#f5e0dc",
    selection="#45475a",
    black="#45475a",
    red="#f38ba8",
    green="#a6e3a1",
    yellow="#f9e2af",
    blue="#89b4fa",
    magenta="#f5c2e7",
    cyan="#94e2d5",
    white="#bac2de",
    bright_black="#585b70",
    bright_red="#f38ba8",
    bright_green="#a6e3a1",
    bright_yellow="#f9e2af",
    bright_blue="#89b4fa",
    bright_magenta="#f5c2e7",
    bright_cyan="#94e2d5",
    bright_white="#cdd6f4",
    primary="#89b4fa",
    secondary="#a6e3a1",
    accent="#f5c2e7",
    info="#94e2d5",
    success="#a6e3a1",
    warning="#f9e2af",
    error="#f38ba8",
    muted="#6c7086",
    border="#313244",
    highlight="#45475a",
    link="#94e2d5",
    code="#f5c2e7",
)

GRUVBOX_THEME = Theme(
    name="gruvbox",
    display_name="Gruvbox Dark",
    type=ThemeType.DARK,
    description="Retro groove color scheme",
    background="#282828",
    foreground="#ebdbb2",
    cursor="#ebdbb2",
    selection="#504945",
    black="#282828",
    red="#cc241d",
    green="#98971a",
    yellow="#d79921",
    blue="#458588",
    magenta="#b16286",
    cyan="#689d6a",
    white="#a89984",
    bright_black="#928374",
    bright_red="#fb4934",
    bright_green="#b8bb26",
    bright_yellow="#fabd2f",
    bright_blue="#83a598",
    bright_magenta="#d3869b",
    bright_cyan="#8ec07c",
    bright_white="#ebdbb2",
    primary="#83a598",
    secondary="#b8bb26",
    accent="#d3869b",
    info="#8ec07c",
    success="#b8bb26",
    warning="#fabd2f",
    error="#fb4934",
    muted="#7c6f64",
    border="#3c3836",
    highlight="#504945",
    link="#8ec07c",
    code="#d3869b",
)

NORD_THEME = Theme(
    name="nord",
    display_name="Nord",
    type=ThemeType.DARK,
    description="Arctic, north-bluish color palette",
    background="#2e3440",
    foreground="#d8dee9",
    cursor="#d8dee9",
    selection="#434c5e",
    black="#3b4252",
    red="#bf616a",
    green="#a3be8c",
    yellow="#ebcb8b",
    blue="#81a1c1",
    magenta="#b48ead",
    cyan="#88c0d0",
    white="#e5e9f0",
    bright_black="#4c566a",
    bright_red="#bf616a",
    bright_green="#a3be8c",
    bright_yellow="#ebcb8b",
    bright_blue="#81a1c1",
    bright_magenta="#b48ead",
    bright_cyan="#8fbcbb",
    bright_white="#eceff4",
    primary="#81a1c1",
    secondary="#a3be8c",
    accent="#b48ead",
    info="#88c0d0",
    success="#a3be8c",
    warning="#ebcb8b",
    error="#bf616a",
    muted="#616e88",
    border="#3b4252",
    highlight="#434c5e",
    link="#88c0d0",
    code="#b48ead",
)

DRACULA_THEME = Theme(
    name="dracula",
    display_name="Dracula",
    type=ThemeType.DARK,
    description="Dark theme with vibrant colors",
    background="#282a36",
    foreground="#f8f8f2",
    cursor="#f8f8f2",
    selection="#44475a",
    black="#21222c",
    red="#ff5555",
    green="#50fa7b",
    yellow="#f1fa8c",
    blue="#bd93f9",
    magenta="#ff79c6",
    cyan="#8be9fd",
    white="#f8f8f2",
    bright_black="#6272a4",
    bright_red="#ff6e6e",
    bright_green="#69ff94",
    bright_yellow="#ffffa5",
    bright_blue="#d6acff",
    bright_magenta="#ff92df",
    bright_cyan="#a4ffff",
    bright_white="#ffffff",
    primary="#bd93f9",
    secondary="#50fa7b",
    accent="#ff79c6",
    info="#8be9fd",
    success="#50fa7b",
    warning="#f1fa8c",
    error="#ff5555",
    muted="#6272a4",
    border="#44475a",
    highlight="#44475a",
    link="#8be9fd",
    code="#ff79c6",
)

SOLARIZED_DARK_THEME = Theme(
    name="solarized-dark",
    display_name="Solarized Dark",
    type=ThemeType.DARK,
    description="Precision colors for machines and people",
    background="#002b36",
    foreground="#839496",
    cursor="#839496",
    selection="#073642",
    black="#073642",
    red="#dc322f",
    green="#859900",
    yellow="#b58900",
    blue="#268bd2",
    magenta="#d33682",
    cyan="#2aa198",
    white="#eee8d5",
    bright_black="#002b36",
    bright_red="#cb4b16",
    bright_green="#586e75",
    bright_yellow="#657b83",
    bright_blue="#839496",
    bright_magenta="#6c71c4",
    bright_cyan="#93a1a1",
    bright_white="#fdf6e3",
    primary="#268bd2",
    secondary="#859900",
    accent="#d33682",
    info="#2aa198",
    success="#859900",
    warning="#b58900",
    error="#dc322f",
    muted="#586e75",
    border="#073642",
    highlight="#073642",
    link="#2aa198",
    code="#d33682",
)

GITHUB_LIGHT_THEME = Theme(
    name="github-light",
    display_name="GitHub Light",
    type=ThemeType.LIGHT,
    description="GitHub's light color scheme",
    background="#ffffff",
    foreground="#24292f",
    cursor="#24292f",
    selection="#0969da20",
    black="#24292f",
    red="#cf222e",
    green="#116329",
    yellow="#4d2d00",
    blue="#0969da",
    magenta="#8250df",
    cyan="#1b7c83",
    white="#6e7781",
    bright_black="#57606a",
    bright_red="#a40e26",
    bright_green="#1a7f37",
    bright_yellow="#633c01",
    bright_blue="#218bff",
    bright_magenta="#a475f9",
    bright_cyan="#3192aa",
    bright_white="#8c959f",
    primary="#0969da",
    secondary="#116329",
    accent="#8250df",
    info="#1b7c83",
    success="#116329",
    warning="#9a6700",
    error="#cf222e",
    muted="#6e7781",
    border="#d0d7de",
    highlight="#fff8c5",
    link="#0969da",
    code="#8250df",
)


class ThemeManager:
    """
    Manage themes - loading, switching, and persistence

    Handles theme discovery, loading from JSON, and theme switching.
    Stores current theme preference in config.
    """

    BUILTIN_THEMES = {
        "tokyonight": TOKYONIGHT_THEME,
        "everforest": EVERFOREST_THEME,
        "catppuccin": CATPPUCCIN_THEME,
        "gruvbox": GRUVBOX_THEME,
        "nord": NORD_THEME,
        "dracula": DRACULA_THEME,
        "solarized-dark": SOLARIZED_DARK_THEME,
        "github-light": GITHUB_LIGHT_THEME,
    }

    def __init__(self, custom_themes_dir: Optional[Path] = None):
        """
        Initialize theme manager

        Args:
            custom_themes_dir: Directory for custom theme JSON files
        """
        self.custom_themes_dir = custom_themes_dir or Path.home() / ".groknroll" / "themes"
        self.custom_themes_dir.mkdir(parents=True, exist_ok=True)
        self._custom_themes: dict[str, Theme] = {}
        self._current_theme: Theme = TOKYONIGHT_THEME
        self._load_custom_themes()

    def _load_custom_themes(self):
        """Load custom themes from JSON files"""
        if not self.custom_themes_dir.exists():
            return

        for json_file in self.custom_themes_dir.glob("*.json"):
            try:
                theme = Theme.from_json(json_file)
                self._custom_themes[theme.name] = theme
            except Exception as e:
                # Skip invalid theme files
                pass

    def get_theme(self, name: str) -> Optional[Theme]:
        """Get theme by name"""
        # Check built-in themes first
        if name in self.BUILTIN_THEMES:
            return self.BUILTIN_THEMES[name]

        # Check custom themes
        if name in self._custom_themes:
            return self._custom_themes[name]

        return None

    def list_themes(self) -> list[str]:
        """List all available theme names"""
        return list(self.BUILTIN_THEMES.keys()) + list(self._custom_themes.keys())

    def list_builtin_themes(self) -> list[str]:
        """List built-in theme names"""
        return list(self.BUILTIN_THEMES.keys())

    def list_custom_themes(self) -> list[str]:
        """List custom theme names"""
        return list(self._custom_themes.keys())

    def set_theme(self, name: str) -> bool:
        """
        Set current theme

        Args:
            name: Theme name

        Returns:
            True if theme was set successfully
        """
        theme = self.get_theme(name)
        if theme:
            self._current_theme = theme
            return True
        return False

    def get_current_theme(self) -> Theme:
        """Get current active theme"""
        return self._current_theme

    def preview(self, name: str) -> str:
        """
        Generate preview of theme colors

        Args:
            name: Theme name

        Returns:
            Formatted preview string with color samples
        """
        theme = self.get_theme(name)
        if not theme:
            return f"Theme '{name}' not found"

        lines = [
            f"Theme: {theme.display_name}",
            f"Type: {theme.type.value}",
            f"Description: {theme.description}",
            "",
            "Colors:",
            f"  Primary:   {theme.primary}",
            f"  Secondary: {theme.secondary}",
            f"  Accent:    {theme.accent}",
            f"  Success:   {theme.success}",
            f"  Warning:   {theme.warning}",
            f"  Error:     {theme.error}",
            "",
            "ANSI:",
            f"  Red:     {theme.red}",
            f"  Green:   {theme.green}",
            f"  Yellow:  {theme.yellow}",
            f"  Blue:    {theme.blue}",
            f"  Magenta: {theme.magenta}",
            f"  Cyan:    {theme.cyan}",
        ]
        return "\n".join(lines)

    def save_custom_theme(self, theme: Theme) -> bool:
        """
        Save custom theme to JSON file

        Args:
            theme: Theme to save

        Returns:
            True if saved successfully
        """
        try:
            theme_path = self.custom_themes_dir / f"{theme.name}.json"
            with open(theme_path, "w") as f:
                json.dump(theme.to_dict(), f, indent=2)
            self._custom_themes[theme.name] = theme
            return True
        except Exception:
            return False

    def delete_custom_theme(self, name: str) -> bool:
        """
        Delete custom theme

        Args:
            name: Theme name

        Returns:
            True if deleted successfully
        """
        if name not in self._custom_themes:
            return False

        try:
            theme_path = self.custom_themes_dir / f"{name}.json"
            if theme_path.exists():
                theme_path.unlink()
            del self._custom_themes[name]
            return True
        except Exception:
            return False


# Convenience functions

def create_theme_manager(custom_dir: Optional[Path] = None) -> ThemeManager:
    """
    Create a theme manager with optional custom directory

    Args:
        custom_dir: Directory for custom themes

    Returns:
        Configured ThemeManager
    """
    return ThemeManager(custom_themes_dir=custom_dir)


def get_default_theme() -> Theme:
    """Get default theme (Tokyo Night)"""
    return TOKYONIGHT_THEME


def list_available_themes() -> list[str]:
    """List all available built-in theme names"""
    return list(ThemeManager.BUILTIN_THEMES.keys())
