"""Clipboard integration for Wayland using wl-copy."""

import subprocess
import shutil

from rich.console import Console


console = Console()


class ClipboardManager:
    """Manages clipboard operations for Wayland."""
    
    def __init__(self):
        """Initialize clipboard manager."""
        self.wl_copy_available = self._check_wl_copy()
        
    def _check_wl_copy(self):
        """Check if wl-copy is available.
        
        Returns:
            bool: True if wl-copy is available
        """
        if shutil.which("wl-copy"):
            return True
        else:
            console.print("[yellow]Warning: wl-copy not found. Clipboard integration disabled.[/yellow]")
            console.print("[dim]Install with: sudo apt install wl-clipboard[/dim]")
            return False
            
    def copy_text(self, text):
        """Copy text to Wayland clipboard.

        Args:
            text: Text to copy

        Returns:
            bool: True if successful
        """
        if not self.wl_copy_available:
            console.print("[red]Cannot copy to clipboard: wl-copy not available[/red]")
            return False

        if not text:
            console.print("[yellow]No text to copy[/yellow]")
            return False

        try:
            process = subprocess.run(
                ["wl-copy", "--foreground"],
                input=text,
                text=True,
                capture_output=True,
                check=True,
                timeout=2.0
            )
            console.print(f"[green]Text copied to clipboard ({len(text)} characters)[/green]")
            return True
        except subprocess.TimeoutExpired:
            console.print(f"[green]Text copied to clipboard ({len(text)} characters)[/green]")
            return True
        except subprocess.CalledProcessError as e:
            console.print(f"[red]Failed to copy to clipboard: {e}[/red]")
            if e.stderr:
                console.print(f"[red]Error: {e.stderr}[/red]")
            return False
        except Exception as e:
            console.print(f"[red]Error copying to clipboard: {e}[/red]")
            return False
