"""System clipboard read/write support for Windows, macOS, and Linux."""

import platform
import subprocess


def read_clipboard() -> str:
    """Read text from the system clipboard.

    Uses platform-appropriate commands:
      - Windows: powershell Get-Clipboard
      - macOS: pbpaste
      - Linux: xclip -selection clipboard -o

    Returns:
        Clipboard text, or empty string on any failure.
    """
    system = platform.system()
    try:
        if system == "Windows":
            result = subprocess.run(
                ["powershell", "-command", "Get-Clipboard"],
                capture_output=True,
                text=True,
                timeout=5,
            )
        elif system == "Darwin":
            result = subprocess.run(
                ["pbpaste"],
                capture_output=True,
                text=True,
                timeout=5,
            )
        elif system == "Linux":
            result = subprocess.run(
                ["xclip", "-selection", "clipboard", "-o"],
                capture_output=True,
                text=True,
                timeout=5,
            )
        else:
            return ""

        if result.returncode != 0:
            return ""
        return result.stdout
    except Exception:
        return ""


def write_clipboard(text: str) -> bool:
    """Write text to the system clipboard.

    Uses platform-appropriate commands:
      - Windows: powershell Set-Clipboard
      - macOS: pbcopy
      - Linux: xclip -selection clipboard

    Args:
        text: The text to write to the clipboard.

    Returns:
        True on success, False on failure.
    """
    system = platform.system()
    try:
        if system == "Windows":
            cmd = ["powershell", "-command", "Set-Clipboard"]
        elif system == "Darwin":
            cmd = ["pbcopy"]
        elif system == "Linux":
            cmd = ["xclip", "-selection", "clipboard"]
        else:
            return False

        result = subprocess.run(
            cmd,
            input=text,
            capture_output=True,
            text=True,
            timeout=5,
        )
        return result.returncode == 0
    except Exception:
        return False
