
    ͚h                     T    d Z ddlZddlZddlmZmZmZ ddlmZ  G d d          Z	dS )a  
Paste Text Primitive Operation

This module provides realistic clipboard paste functionality for browser automation.
Simulates human-like pasting with:
- Natural delays before/after paste
- Occasional fumbles (miss the hotkey, retry)
- Clearing existing content first
- Realistic timing variations

Use this for:
- Long text content (articles, code blocks)
- URLs and pre-formatted content
- Bulk text entry (faster than typing)

Use type_text.py for:
- Short form inputs (search queries, usernames)
- When typing animation is desired
    N)DictAnyOptional)Pagec                   f    e Zd ZdZd Z	 	 ddededee         de	d	e
eef         f
d
Zded	dfdZdS )	PasteTexta  
    Paste Text with Human-like Behavior

    Implements realistic clipboard paste that mimics human behavior:
    - Clears existing content (Ctrl+A, Backspace)
    - Natural delay before paste (hand positioning)
    - Occasional "fumbles" when pressing Ctrl+V
    - Brief verification pause after paste
    - Random timing variations

    Usage:
        paster = PasteText()
        result = await paster.paste(page, text)
    c                 $    t          d           dS )z"Initialize the paste text handler.u   📋 PasteText initializedN)print)selfs    =/home/byschii/byschiidev/penelope/lib/primitive/paste_text.py__init__zPasteText.__init__,   s    *+++++    NTpagetextdelay_beforeclear_existingreturnc                 0  K   	 t          d|dd          t          |          dk    rdnd d           |r|                     |           d{V  |t          j        dd          }t          j        |d	z             d{V  d
}t          j                    dk     rd}t          d           |j                            d           d{V  t          j        t          j        dd                     d{V  |j        	                    d           d{V  t          j        t          j        dd                     d{V  |
                    d|           d{V  t          j        dd          }t          j        |d	z             d{V  dt          |          |||j        d}t          dt          |           d|rdnd            |S # t          $ r0}d
t          |          d}	t          d|            |	cY d}~S d}~ww xY w)a  
        Paste text using clipboard (Ctrl+V) at the currently focused element.

        IMPORTANT: The target element should already be clicked/focused before calling this method.
        This method will clear any existing text in the focused element before pasting.

        Args:
            page (Page): Playwright page to use
            text (str): Text to paste
            delay_before (Optional[int]): Delay before pasting in ms (None = random human-like)
            clear_existing (bool): Whether to clear existing content first (default: True)

        Returns:
            Dict containing paste result and text information
        u   📋 Pasting text: 'N2   z... 'd   i  i  F皙?Tu    🤷 Fumbled Ctrl+V, retrying...Control皙?333333?g333333?a  
                (text) => {
                    const el = document.activeElement;
                    if (el) {
                        // For input/textarea elements
                        if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
                            el.value = text;
                            // Trigger input event so page detects the change
                            el.dispatchEvent(new Event('input', { bubbles: true }));
                            el.dispatchEvent(new Event('change', { bubbles: true }));
                        } 
                        // For contenteditable elements
                        else if (el.isContentEditable) {
                            el.textContent = text;
                            // Trigger input event
                            el.dispatchEvent(new Event('input', { bubbles: true }));
                        }
                    }
                }
               )successtext_lengthfumbleddelay_before_msurlu   ✅ Text pasted: z charactersz (after fumble))r   erroru   ❌ Text pasting failed: )r
   len_clear_focused_elementrandomuniformasynciosleepkeyboarddownupevaluater"   	Exceptionstr)
r   r   r   r   r   r    verify_delayresulteerror_results
             r   pastezPasteText.paste0   s     ,I	 VcrcVSYY^^EEQSVVVWWW  811$777777777 #%~c377 -t 3444444444 G}%%8999 m((333333333mFN4$>$>?????????m&&y111111111 mFN4$>$>?????????
 -- !& '        , ">"c22L-t 3444444444  "4yy"#/x F bc$iibbQX<`<M<M^`bbcccM 	  	  	  Q L 1a11222	 s   GG 
H%%H
HHc                 T  K   	 |                     d           d{V }|rZ|                                rGt          d           |j                            d           d{V  t          j        t          j        dd                     d{V  |j        	                    d           d{V  t          j        t          j        dd                     d{V  |j        
                    d           d{V  t          j        t          j        d	d
                     d{V  |j        	                    d           d{V  t          j        t          j        dd                     d{V  dS dS dS # t          $ r}t          d|            Y d}~dS d}~ww xY w)z
        Clear any existing text in the focused element using Ctrl+A, Backspace.

        Args:
            page (Page): Playwright page to use
        z
                () => {
                    const el = document.activeElement;
                    return el && (el.value !== undefined ? el.value : el.textContent);
                }
            Nu1   🗑️ Clearing existing text in focused elementr   g{Gz?g{Gz?KeyAg{Gz?r   r   	Backspaceg{Gz?r   u.   ⚠️ Could not check/clear focused element: )r-   stripr
   r*   r+   r(   r)   r&   r'   pressr,   r.   )r   r   focused_valuer2   s       r   r%   z PasteText._clear_focused_element   s8     	H"&-- 1 # #      M  @!4!4!6!6 @JKKK m((333333333mFN4$>$>?????????m))&111111111mFN4$>$>?????????m&&y111111111mFN4$>$>????????? m))+666666666mFN4$>$>???????????@ @ @ @  	H 	H 	HF1FFGGGGGGGGG	Hs   E6F   
F'
F""F')NT)__name__
__module____qualname____doc__r   r   r/   r   intboolr   r   r4   r%    r   r   r   r      s         , , , '+#_  _ _  _  sm	_ 
 _  
c3h_  _  _  _ B H  H$  H  H  H  H  H  Hr   r   )
r>   r(   r&   typingr   r   r   patchright.async_apir   r   rA   r   r   <module>rD      s    (   & & & & & & & & & & % % % % % %UH UH UH UH UH UH UH UH UH UHr   