"""Service for generating editor color themes."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Any

    from portal.core.domain.models import WorktreeColor


class ColorThemeService:
    """Service for generating editor color themes."""

    def generate_cursor_theme(self, color: WorktreeColor) -> dict[str, Any]:
        """Generate Cursor/VSCode color customizations."""
        # Darken/lighten the base color for variations
        darker = self._darken_hex(color.hex, 0.3)
        lighter = self._lighten_hex(color.hex, 0.3)
        subtle = self._lighten_hex(color.hex, 0.1)

        return {
            "workbench.colorCustomizations": {
                # Title bar
                "titleBar.activeBackground": color.hex,
                "titleBar.activeForeground": "#FFFFFF" if color.is_dark else "#000000",
                "titleBar.inactiveBackground": darker,
                "titleBar.inactiveForeground": "#CCCCCC",
                # Status bar
                "statusBar.background": color.hex,
                "statusBar.foreground": "#FFFFFF" if color.is_dark else "#000000",
                "statusBar.debuggingBackground": lighter,
                # Activity bar
                "activityBar.background": darker,
                "activityBar.foreground": "#FFFFFF",
                "activityBar.activeBorder": color.hex,
                # Sidebar - only customize header, not foreground
                "sideBarSectionHeader.background": darker,
                "sideBarSectionHeader.foreground": "#FFFFFF" if color.is_dark else "#000000",
                "sideBarTitle.foreground": subtle,
                # Tabs
                "tab.activeBorderTop": color.hex,
                "tab.unfocusedActiveBorderTop": lighter,
                # Editor
                "editorGroupHeader.tabsBackground": darker,
                "editorGroup.border": color.hex,
                # Panel
                "panel.border": color.hex,
                "panelTitle.activeBorder": color.hex,
                # Terminal
                "terminal.border": color.hex,
                "terminalCursor.foreground": color.hex,
            }
        }

    def generate_vscode_theme(self, color: WorktreeColor) -> dict[str, Any]:
        """Generate VSCode-specific color customizations."""
        # VSCode and Cursor use the same format
        return self.generate_cursor_theme(color)

    def generate_iterm_profile(self, color: WorktreeColor) -> dict[str, Any]:
        """Generate iTerm2 dynamic profile."""
        return {
            "Profiles": [
                {
                    "Name": f"Portal - {color.name}",
                    "Guid": f"portal-{color.name.lower()}",
                    "Background Color": {
                        "Red Component": color.rgb[0] / 255.0 * 0.1,  # Darken for background
                        "Green Component": color.rgb[1] / 255.0 * 0.1,
                        "Blue Component": color.rgb[2] / 255.0 * 0.1,
                    },
                    "Badge Color": {
                        "Red Component": color.rgb[0] / 255.0,
                        "Green Component": color.rgb[1] / 255.0,
                        "Blue Component": color.rgb[2] / 255.0,
                        "Alpha Component": 0.5,
                    },
                    "Cursor Color": {
                        "Red Component": color.rgb[0] / 255.0,
                        "Green Component": color.rgb[1] / 255.0,
                        "Blue Component": color.rgb[2] / 255.0,
                    },
                    "Tab Color": {
                        "Red Component": color.rgb[0] / 255.0,
                        "Green Component": color.rgb[1] / 255.0,
                        "Blue Component": color.rgb[2] / 255.0,
                    },
                    "Use Tab Color": True,
                    "Tags": ["portal", color.name.lower()],
                }
            ]
        }

    def generate_terminal_profile(self, color: WorktreeColor) -> dict[str, Any]:
        """Generate Terminal.app profile."""
        return {
            "name": f"Portal - {color.name}",
            "type": "Window Settings",
            "BackgroundColor": [
                color.rgb[0] / 255.0 * 0.1,  # Darken for background
                color.rgb[1] / 255.0 * 0.1,
                color.rgb[2] / 255.0 * 0.1,
            ],
            "CursorColor": [
                color.rgb[0] / 255.0,
                color.rgb[1] / 255.0,
                color.rgb[2] / 255.0,
            ],
            "SelectionColor": [
                color.rgb[0] / 255.0 * 0.3,
                color.rgb[1] / 255.0 * 0.3,
                color.rgb[2] / 255.0 * 0.3,
            ],
        }

    def generate_hyper_theme(self, color: WorktreeColor) -> dict[str, Any]:
        """Generate Hyper terminal theme configuration."""
        return {
            "backgroundColor": self._lighten_hex(color.hex, 0.9),  # Very light background
            "foregroundColor": "#000000",
            "cursorColor": color.hex,
            "borderColor": color.hex,
            "selectionColor": self._lighten_hex(color.hex, 0.7),
            "colors": {
                "black": "#000000",
                "red": "#ff0000",
                "green": "#00ff00",
                "yellow": "#ffff00",
                "blue": color.hex,  # Use our color as blue
                "magenta": "#ff00ff",
                "cyan": "#00ffff",
                "white": "#ffffff",
                "lightBlack": "#808080",
                "lightRed": "#ff8080",
                "lightGreen": "#80ff80",
                "lightYellow": "#ffff80",
                "lightBlue": self._lighten_hex(color.hex, 0.3),
                "lightMagenta": "#ff80ff",
                "lightCyan": "#80ffff",
                "lightWhite": "#ffffff",
            },
        }

    def generate_css_variables(self, color: WorktreeColor) -> dict[str, str]:
        """Generate CSS custom properties for web interfaces."""
        base_name = color.name.lower().replace(" ", "-")
        darker = self._darken_hex(color.hex, 0.2)
        lighter = self._lighten_hex(color.hex, 0.2)

        return {
            f"--portal-color-{base_name}": color.hex,
            f"--portal-color-{base_name}-dark": darker,
            f"--portal-color-{base_name}-light": lighter,
            f"--portal-color-{base_name}-rgb": f"{color.rgb[0]}, {color.rgb[1]}, {color.rgb[2]}",
            f"--portal-color-{base_name}-hsl": f"{color.hsl[0]}, {color.hsl[1]}%, {color.hsl[2]}%",
        }

    def _darken_hex(self, hex_color: str, factor: float) -> str:
        """Darken a hex color by a factor."""
        hex_color = hex_color.lstrip("#")
        rgb = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
        darkened = tuple(max(0, int(c * (1 - factor))) for c in rgb)
        return "#{:02x}{:02x}{:02x}".format(*darkened)

    def _lighten_hex(self, hex_color: str, factor: float) -> str:
        """Lighten a hex color by a factor."""
        hex_color = hex_color.lstrip("#")
        rgb = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
        lightened = tuple(min(255, int(c + (255 - c) * factor)) for c in rgb)
        return "#{:02x}{:02x}{:02x}".format(*lightened)

    def _rgb_to_hex(self, rgb: tuple[int, int, int]) -> str:
        """Convert RGB tuple to hex string."""
        return "#{:02x}{:02x}{:02x}".format(*rgb)
