from __future__ import annotations

import logging
from typing import Callable, Dict, Optional

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QAction, QKeySequence
from PyQt6.QtWidgets import QWidget


class ShortcutManager:
    """
    Widget-scoped shortcut registry.

    Goals:
    - Avoid global shortcut collisions by using WidgetWithChildrenShortcut.
    - Detect accidental duplicate bindings within the same widget and log them.
    """

    def __init__(self, logger: logging.Logger):
        self._logger = logger
        self._registry: Dict[int, Dict[str, QAction]] = {}

    def add(
        self,
        widget: QWidget,
        key: str,
        callback: Callable[[], None],
        description: str = "",
    ) -> Optional[QAction]:
        if widget is None:
            return None

        widget_id = id(widget)
        if widget_id not in self._registry:
            self._registry[widget_id] = {}
            widget.destroyed.connect(lambda *_: self._registry.pop(widget_id, None))

        sequence = QKeySequence(key)
        normalized = sequence.toString(QKeySequence.SequenceFormat.NativeText)
        if normalized in self._registry[widget_id]:
            existing = self._registry[widget_id][normalized]
            self._logger.warning(
                "Shortcut collision (skipped): widget=%s key=%s existing=%s",
                widget.objectName() or widget.__class__.__name__,
                normalized,
                existing.text() if isinstance(existing, QAction) else existing,
            )
            return None

        action = QAction(description or normalized, widget)
        action.setShortcut(sequence)
        action.setShortcutContext(Qt.ShortcutContext.WidgetWithChildrenShortcut)
        action.triggered.connect(callback)
        widget.addAction(action)
        self._registry[widget_id][normalized] = action
        return action





