import logging
import random
from time import sleep

logger = logging.getLogger(__name__)


def ghost_type(device, text: str, speed: str = "normal"):
    """
    Tesla Stealth Ghost Keyboard.
    Bypasses UIAutomator virtual IME completely and sends raw Native InputEvents.
    Features: Variable typing speed, burst chunking, and synthetic human mistakes.
    """
    if not text:
        return

    logger.info(f"⌨️  [Ghost Keyboard] Initiating stealth injection ({len(text)} chars)...")

    # We slice text into variable-sized human bursts
    chunks = []
    i = 0
    while i < len(text):
        if random.random() < 0.15:
            chunk_size = 1  # single letter hunting
        else:
            chunk_size = random.randint(2, 6)  # fluid typing bursts

        chunks.append(text[i : i + chunk_size])
        i += chunk_size

    for idx, chunk in enumerate(chunks):
        # 5% chance of a typo if it's an alphabetical chunk
        if random.random() < 0.05 and len(chunk) >= 2 and chunk[-1].isalpha():
            typo_letter = random.choice("abcdefghijklmnopqrstuvwxyz")
            # Add typo instead of actual last letter
            typo_chunk = chunk[:-1] + typo_letter
            _adb_inject_text(device, typo_chunk)

            # Realize mistake
            sleep(random.uniform(0.2, 0.45))

            # Send Backspace (KEYCODE_DEL = 67)
            device.shell("input keyevent 67")
            sleep(random.uniform(0.1, 0.25))

            # Inject the correct character
            _adb_inject_text(device, chunk[-1])
        else:
            _adb_inject_text(device, chunk)

        if speed == "fast":
            sleep(random.uniform(0.01, 0.05))
            continue

        # Realistic pause between semantic bursts (humans think while typing)
        if chunk.endswith((" ", ".", ",", "!", "?")):
            sleep(random.uniform(0.2, 0.5))
        else:
            sleep(random.uniform(0.05, 0.18))

    logger.debug("⌨️  [Ghost Keyboard] Injection complete.")


def _adb_inject_text(device, text: str):
    if not text:
        return

    # For Android `input text`, spaces must be mapped to %s
    # Single quotes need to be bash escaped since we wrap the string in ''
    # Special characters like & | > < \ ( ) { } ! must be carefully handled.
    # The safest way is to let shell loop over characters or strictly replace.
    safe_text = text.replace(" ", "%s").replace("'", "\\'")

    # Send through Android's native InputManager
    try:
        device.shell(["input", "text", safe_text])
    except Exception as e:
        logger.debug(f"[Ghost Keyboard] Native injection failed: {e}")
