"""
Atajos de teclado para CTkEntry.

Agrega:
  Ctrl+Backspace  — eliminar la palabra anterior al cursor
  Ctrl+Delete     — eliminar la palabra siguiente al cursor
  Ctrl+A          — seleccionar todo el texto
"""
import customtkinter as ctk


def _ctrl_backspace(event):
    w = event.widget
    pos = w.index("insert")
    text = w.get()[:pos]
    stripped = text.rstrip()
    new_pos = stripped.rfind(" ") + 1 if stripped else 0
    if new_pos < pos:
        w.delete(new_pos, pos)
    return "break"


def _ctrl_delete(event):
    w = event.widget
    pos = w.index("insert")
    text = w.get()[pos:]
    stripped = text.lstrip()
    offset = len(text) - len(stripped)
    idx = stripped.find(" ")
    end = pos + offset + (idx if idx >= 0 else len(stripped))
    if end > pos:
        w.delete(pos, end)
    return "break"


def _ctrl_a(event):
    w = event.widget
    w.select_range(0, "end")
    w.icursor("end")
    return "break"


def bind_entry(entry: ctk.CTkEntry):
    """Aplica atajos de teclado a un CTkEntry."""
    inner = getattr(entry, "_entry", entry)
    inner.bind("<Control-BackSpace>", _ctrl_backspace)
    inner.bind("<Control-Delete>",    _ctrl_delete)
    inner.bind("<Control-a>",         _ctrl_a)
    inner.bind("<Control-A>",         _ctrl_a)
