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

import os
import subprocess
import shutil
import time

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()
        self.ydotool_available = self._check_ydotool()
    
    def check_requirements(self, require_paste=False):
        """Check if all required tools are installed.
        
        Args:
            require_paste: If True, also check for ydotool
            
        Returns:
            bool: True if all requirements are met
        """
        missing = []
        
        if not self.wl_copy_available:
            missing.append("wl-copy (wl-clipboard)")
        
        if require_paste and not self.ydotool_available:
            missing.append("ydotool")
        
        if missing:
            console.print("[red]Missing required tools:[/red]")
            for tool in missing:
                console.print(f"  - {tool}")
            console.print("\n[dim]Install with:[/dim]")
            console.print("  sudo apt install wl-clipboard")
            if require_paste:
                console.print("  sudo apt install ydotool")
            return False
        
        # Check uinput permissions if paste is required
        if require_paste and self.ydotool_available:
            if not self._check_uinput_permissions():
                return False
        
        return True
    
    def _check_uinput_permissions(self):
        """Check if user has access to /dev/uinput for ydotool.
        
        Returns:
            bool: True if uinput is accessible
        """
        # Check if /dev/uinput exists and is accessible
        if not os.path.exists("/dev/uinput"):
            console.print("[red]ydotool setup issue: /dev/uinput not found[/red]")
            return False
        
        if not os.access("/dev/uinput", os.R_OK | os.W_OK):
            console.print("[red]ydotool permission issue: Cannot access /dev/uinput[/red]")
            console.print("\n[dim]To fix ydotool permissions:[/dim]")
            console.print("  1. Add your user to the 'input' group:")
            console.print("     sudo usermod -aG input $USER")
            console.print("  2. Set uinput permissions:")
            console.print("     echo 'KERNEL==\"uinput\", MODE=\"0660\", GROUP=\"input\"' | sudo tee /etc/udev/rules.d/99-uinput.rules")
            console.print("  3. Reload udev rules:")
            console.print("     sudo udevadm control --reload-rules && sudo udevadm trigger")
            console.print("  4. Log out and log back in for group changes to take effect")
            return False
        
        return True
        
    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 _check_ydotool(self):
        """Check if ydotool is available.
        
        Returns:
            bool: True if ydotool is available
        """
        if shutil.which("ydotool"):
            return True
        else:
            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

    def type_text(self, text):
        """Type text directly into the active window using ydotool.

        Args:
            text: Text to type

        Returns:
            bool: True if successful
        """
        if not self.ydotool_available:
            console.print("[red]Cannot type: ydotool not available[/red]")
            console.print("[dim]Install with: sudo apt install ydotool[/dim]")
            return False

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

        try:
            # Check if last word is 'enter' or 'go' (ignoring trailing punctuation)
            import re
            text_stripped = text.rstrip('.!? ')
            words = text_stripped.split()
            send_enter = False
            text_to_type = text

            if words and words[-1].lower() in ('enter', 'go'):
                send_enter = True
                # Remove the last word from the text to type
                text_to_type = text[:text.rfind(words[-1])].rstrip()

            # Small delay to ensure focus is on target window
            time.sleep(0.1)

            if text_to_type:
                # Type the text directly using ydotool
                subprocess.run(
                    ["ydotool", "type", text_to_type],
                    capture_output=True,
                    check=True,
                    timeout=10.0
                )

            if send_enter:
                # Send Enter key using ydotool
                subprocess.run(
                    ["ydotool", "key", "Enter"],
                    capture_output=True,
                    check=True,
                    timeout=2.0
                )
                console.print(f"[green]Text typed into active window ({len(text_to_type)} characters) + Enter[/green]")
            else:
                console.print(f"[green]Text typed into active window ({len(text_to_type)} characters)[/green]")
            return True
        except subprocess.CalledProcessError as e:
            error_msg = e.stderr.decode() if isinstance(e.stderr, bytes) else str(e.stderr)

            if "uinput" in error_msg.lower() or "SIGABRT" in str(e):
                console.print("[red]ydotool failed: Permission denied for /dev/uinput[/red]")
                console.print("\n[dim]To fix this issue:[/dim]")
                console.print("  1. Add your user to the 'input' group:")
                console.print("     sudo usermod -aG input $USER")
                console.print("  2. Set uinput permissions:")
                console.print("     echo 'KERNEL=\"uinput\", MODE=\"0660\", GROUP=\"input\"' | sudo tee /etc/udev/rules.d/99-uinput.rules")
                console.print("  3. Reload udev rules:")
                console.print("     sudo udevadm control --reload-rules && sudo udevadm trigger")
                console.print("  4. Log out and log back in for group changes to take effect")
            else:
                console.print(f"[red]Failed to type: {e}[/red]")
                if e.stderr:
                    console.print(f"[red]Error: {error_msg}[/red]")
            return False
        except Exception as e:
            console.print(f"[red]Error typing: {e}[/red]")
            return False
