#!/usr/bin/env python3
"""
Press Tab Primitive Operation

This module provides realistic Tab key press functionality for browser automation.
Simulates human-like key press with natural timing.
"""

import asyncio
import random
from typing import Dict, Any
from patchright.async_api import Page


class PressTab:
    """
    Press Tab Key with Human-like Timing

    Implements realistic Tab key press behavior:
    - Small pre-press delay (hesitation)
    - Natural key press duration
    - Post-press delay for UI response

    Usage:
        presser = PressTab()
        result = await presser.press(page, base_delay=50)
    """

    def __init__(self):
        """Initialize the press tab handler."""
        print("⇥ PressTab initialized")

    async def press(self, page: Page, with_shift:bool = False, base_delay: int = 50) -> Dict[str, Any]:
        """
        Press the Tab key to move focus to the next element.

        IMPORTANT: The page should be in a state where Tab navigation is expected.

        Args:
            page (Page): Playwright page to use
            base_delay (int): Base delay in milliseconds for timing (default: 50)

        Returns:
            Dict containing press result and timing information
        """
        try:
            print("⇥ Pressing Tab key")

            # Small pre-press hesitation (human doesn't immediately press Tab)
            pre_delay = base_delay * random.uniform(0.5, 1.5)
            await asyncio.sleep(pre_delay / 1000)

            # Press Tab key
            if with_shift:
                await page.keyboard.press('Shift+Tab')
            else:
                await page.keyboard.press('Tab')

            # Post-press delay (wait for UI to respond)
            post_delay = base_delay * random.uniform(1.0, 2.0)
            await asyncio.sleep(post_delay / 1000)

            result = {
                "success": True,
                "key": "Tab" if not with_shift else "Shift+Tab",
                "url": page.url
            }

            print("✅ Tab key pressed")
            return result

        except Exception as e:
            error_result = {
                "success": False,
                "error": str(e)
            }
            print(f"❌ Tab key press failed: {e}")
            return error_result
