"""
Input Injection Utility.
========================

This module handles the simulation of user input to 'paste' text 
into the currently active application. It relies on clipboard manipulation
combined with keyboard shortcuts (Ctrl+V).
"""

import pyperclip
import keyboard
import time
import logging

class InputInjector:
    """
    Static utility class for text injection.
    """

    @staticmethod
    def inject_text(text: str, method: str = "Clipboard Paste", speed: int = 100):
        """
        Injects the provided text into the currently focused UI element.

        Args:
            text (str): The string to inject.
            method (str): "Clipboard Paste" or "Simulate Typing"
            speed (int): Chars per minute for typing.
        """
        if not text:
            return

        try:
            logging.info(f"Injecting text via {method}...")

            if method == "Simulate Typing":
                # CPM to delay calculation
                # 60 seconds / speed chars = seconds per char
                delay = 60.0 / max(1, speed)
                keyboard.write(text, delay=delay)
                
            else:
                # Default: Clipboard Paste
                # We purposefully do not backup/restore the clipboard 
                # because it is slow and error-prone with large clipboard contents.
                # Ideally, we accept that this tool overwrites the clipboard.
                
                # Step 1: Copy to Clipboard
                pyperclip.copy(text)
                
                # Step 2: Tiny wait to ensure OS clipboard update propagates
                time.sleep(0.1)
                
                # Step 3: Send Paste Command
                keyboard.send('ctrl+v')
            
            logging.info("Text injection complete.")
            
        except Exception as e:
            logging.error(f"Failed to inject text: {e}")
