"""macOS text input emulation via Quartz CGEvent.

Uses CGEventKeyboardSetUnicodeString to inject arbitrary Unicode characters
(same technique as Муравей SEB stealth mode — works with all character sets).
"""

from __future__ import annotations

import logging
import time

log = logging.getLogger(__name__)


def type_char(char: str) -> None:
    """Inject a single Unicode character into the focused window.

    Uses real keycode 0 (Space placeholder) with Unicode string override —
    this works for characters outside the current keyboard layout.
    """
    try:
        import Quartz  # type: ignore[import]

        # Use None source (hardware-originated events) — passes SEB filters
        KEY_CODE = 0x31  # Space keycode as carrier for Unicode override

        ev_down = Quartz.CGEventCreateKeyboardEvent(None, KEY_CODE, True)
        ev_up = Quartz.CGEventCreateKeyboardEvent(None, KEY_CODE, False)

        # Override the character delivered by the event
        Quartz.CGEventKeyboardSetUnicodeString(ev_down, len(char), char)
        Quartz.CGEventKeyboardSetUnicodeString(ev_up, len(char), char)

        Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev_down)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev_up)

    except ImportError:
        log.warning("Quartz not available — falling back to AppleScript keystroke")
        _type_char_applescript(char)
    except Exception as exc:
        log.error("CGEvent type_char failed for %r: %s", char, exc)


def _type_char_applescript(char: str) -> None:
    """Fallback: type a character via AppleScript keystroke."""
    import subprocess

    # Escape special chars for AppleScript
    safe = char.replace('"', '\\"').replace("\\", "\\\\")
    try:
        subprocess.run(
            ["osascript", "-e", f'tell application "System Events" to keystroke "{safe}"'],
            timeout=3,
        )
    except Exception as exc:
        log.error("AppleScript keystroke failed: %s", exc)


def type_text(text: str, delay_ms: int = 30) -> None:
    """Type *text* character by character with *delay_ms* between each."""
    delay = delay_ms / 1000.0
    for char in text:
        type_char(char)
        if delay > 0:
            time.sleep(delay)


def type_text_stealth(text: str) -> None:
    """Type text with stealth mode delays for SEB/CSCA evasion.

    Uses 30-70ms per character + 100-200ms extra after spaces,
    matching Муравей's SEB-tested STEALTH mode parameters.
    """
    import random

    delay_per_char = (0.030, 0.070)
    delay_per_space = (0.100, 0.200)
    for char in text:
        type_char(char)
        delay = random.uniform(*delay_per_char)
        if char == " ":
            delay += random.uniform(*delay_per_space)
        time.sleep(delay)
