"""Clipboard helper that works on Wayland (wl-copy), X11 (xclip / xsel),
and as a last resort falls back to Textual's built-in copy_to_clipboard().
"""
from __future__ import annotations

import subprocess


def copy_to_clipboard(text: str) -> None:
    """Copy *text* to the system clipboard using the best available tool."""
    for attempt in (_try_wl_copy, _try_xclip, _try_xsel):
        if attempt(text):
            return
    # Nothing worked — silently ignore; the notify toast will still show.


def _try_wl_copy(text: str) -> bool:
    try:
        subprocess.run(
            ["wl-copy"],
            input=text.encode(),
            check=True,
            timeout=2,
            capture_output=True,
        )
        return True
    except Exception:
        return False


def _try_xclip(text: str) -> bool:
    try:
        subprocess.run(
            ["xclip", "-selection", "clipboard"],
            input=text.encode(),
            check=True,
            timeout=2,
            capture_output=True,
        )
        return True
    except Exception:
        return False


def _try_xsel(text: str) -> bool:
    try:
        subprocess.run(
            ["xsel", "--clipboard", "--input"],
            input=text.encode(),
            check=True,
            timeout=2,
            capture_output=True,
        )
        return True
    except Exception:
        return False
