"""Command registry for LikX command palette."""

from dataclasses import dataclass, field
from typing import Callable, List, Optional

from .editor import ToolType
from .i18n import _


@dataclass
class Command:
    """A command that can be executed from the command palette."""

    name: str  # Display name
    keywords: List[str] = field(default_factory=list)  # Search keywords
    callback: Optional[Callable] = None  # Action to execute
    icon: str = ""  # Optional icon/emoji
    shortcut: str = ""  # Display shortcut hint

    def matches(self, query: str) -> bool:
        """Check if command matches search query (case-insensitive)."""
        query = query.lower().strip()
        if not query:
            return True

        # Check name
        if query in self.name.lower():
            return True

        # Check keywords
        for keyword in self.keywords:
            if query in keyword.lower():
                return True

        return False


def build_command_registry(editor_window) -> List[Command]:
    """Build list of all available commands for the palette."""
    commands = []

    # === TOOLS ===
    commands.extend(
        [
            Command(
                _("Pen Tool"),
                ["draw", "pen", "brush", "freehand"],
                lambda: editor_window._set_tool(ToolType.PEN),
                "✏️",
                "P",
            ),
            Command(
                _("Highlighter"),
                ["highlight", "marker", "emphasis"],
                lambda: editor_window._set_tool(ToolType.HIGHLIGHTER),
                "🖍️",
                "H",
            ),
            Command(
                _("Arrow Tool"),
                ["arrow", "pointer", "direction"],
                lambda: editor_window._set_tool(ToolType.ARROW),
                "➡️",
                "A",
            ),
            Command(
                _("Text Tool"),
                ["text", "type", "label", "annotation"],
                lambda: editor_window._set_tool(ToolType.TEXT),
                "📝",
                "T",
            ),
            Command(
                _("Blur Tool"),
                ["blur", "privacy", "hide", "obscure"],
                lambda: editor_window._set_tool(ToolType.BLUR),
                "🔍",
                "B",
            ),
            Command(
                _("Pixelate Tool"),
                ["pixelate", "censor", "redact", "mosaic"],
                lambda: editor_window._set_tool(ToolType.PIXELATE),
                "◼️",
                "X",
            ),
            Command(
                _("Rectangle"),
                ["rectangle", "box", "shape", "square"],
                lambda: editor_window._set_tool(ToolType.RECTANGLE),
                "⬜",
                "R",
            ),
            Command(
                _("Ellipse"),
                ["ellipse", "circle", "oval", "round"],
                lambda: editor_window._set_tool(ToolType.ELLIPSE),
                "⭕",
                "E",
            ),
            Command(
                _("Line Tool"),
                ["line", "straight", "segment"],
                lambda: editor_window._set_tool(ToolType.LINE),
                "📏",
                "L",
            ),
            Command(
                _("Crop Tool"),
                ["crop", "trim", "cut", "resize"],
                lambda: editor_window._set_tool(ToolType.CROP),
                "✂️",
                "C",
            ),
            Command(
                _("Eraser"),
                ["eraser", "delete", "remove", "undo drawing"],
                lambda: editor_window._set_tool(ToolType.ERASER),
                "🧹",
                "",
            ),
            Command(
                _("Number Marker"),
                ["number", "marker", "step", "sequence", "counter"],
                lambda: editor_window._set_tool(ToolType.NUMBER),
                "①",
                "N",
            ),
            Command(
                _("Measure Tool"),
                ["measure", "ruler", "distance", "size", "dimension", "pixel"],
                lambda: editor_window._set_tool(ToolType.MEASURE),
                "📏",
                "M",
            ),
            Command(
                _("Color Picker"),
                ["color", "picker", "eyedropper", "sample", "pipette"],
                lambda: editor_window._set_tool(ToolType.COLORPICKER),
                "💧",
                "I",
            ),
            Command(
                _("Stamp Tool"),
                ["stamp", "emoji", "sticker", "icon", "checkmark"],
                lambda: editor_window._set_tool(ToolType.STAMP),
                "✓",
                "S",
            ),
            Command(
                _("Zoom Tool"),
                ["zoom", "magnify", "enlarge", "scale"],
                lambda: editor_window._set_tool(ToolType.ZOOM),
                "🔍",
                "Z",
            ),
            Command(
                _("Callout Tool"),
                ["callout", "speech", "bubble", "comment", "annotation"],
                lambda: editor_window._set_tool(ToolType.CALLOUT),
                "💬",
                "K",
            ),
        ]
    )

    # === ZOOM ACTIONS ===
    commands.extend(
        [
            Command(
                _("Zoom In"),
                ["zoom in", "enlarge", "bigger", "magnify"],
                lambda: (
                    editor_window.editor_state.zoom_in(),
                    editor_window._update_zoom_label(),
                    editor_window.drawing_area.queue_draw(),
                ),
                "🔎",
                "+",
            ),
            Command(
                _("Zoom Out"),
                ["zoom out", "shrink", "smaller", "reduce"],
                lambda: (
                    editor_window.editor_state.zoom_out(),
                    editor_window._update_zoom_label(),
                    editor_window.drawing_area.queue_draw(),
                ),
                "🔍",
                "-",
            ),
            Command(
                _("Reset Zoom"),
                ["reset zoom", "100%", "actual size", "fit"],
                lambda: (
                    editor_window.editor_state.reset_zoom(),
                    editor_window._update_zoom_label(),
                    editor_window.drawing_area.queue_draw(),
                ),
                "↺",
                "0",
            ),
        ]
    )

    # === ACTIONS ===
    commands.extend(
        [
            Command(
                _("Save"),
                ["save", "export", "file", "disk"],
                editor_window._save,
                "💾",
                "Ctrl+S",
            ),
            Command(
                _("Copy to Clipboard"),
                ["copy", "clipboard", "paste"],
                editor_window._copy_to_clipboard,
                "📋",
                "Ctrl+C",
            ),
            Command(
                _("Upload to Cloud"),
                ["upload", "share", "imgur", "cloud", "link"],
                editor_window._upload,
                "☁️",
                "",
            ),
            Command(
                _("Undo"),
                ["undo", "back", "revert", "mistake"],
                editor_window._undo,
                "↩️",
                "Ctrl+Z",
            ),
            Command(
                _("Redo"),
                ["redo", "forward", "repeat"],
                editor_window._redo,
                "↪️",
                "Ctrl+Y",
            ),
            Command(
                _("Clear All Annotations"),
                ["clear", "reset", "delete all", "clean"],
                editor_window._clear,
                "🗑️",
                "",
            ),
        ]
    )

    # === EFFECTS ===
    commands.extend(
        [
            Command(
                _("Add Shadow"),
                ["shadow", "effect", "drop shadow"],
                editor_window._apply_shadow,
                "🌑",
                "",
            ),
            Command(
                _("Add Border"),
                ["border", "frame", "outline"],
                editor_window._apply_border,
                "🔲",
                "",
            ),
            Command(
                _("Round Corners"),
                ["round", "corners", "radius", "curved"],
                editor_window._apply_round_corners,
                "⬜",
                "",
            ),
        ]
    )

    # === PREMIUM FEATURES ===
    commands.extend(
        [
            Command(
                _("OCR - Extract Text"),
                ["ocr", "text", "extract", "read", "recognize"],
                editor_window._extract_text,
                "📖",
                "",
            ),
            Command(
                _("Pin to Desktop"),
                ["pin", "float", "always on top", "sticky"],
                editor_window._pin_to_desktop,
                "📌",
                "",
            ),
        ]
    )

    return commands
