import subprocess
import sys
from typing import Protocol


class InputBackend(Protocol):
    def type_text(self, text: str) -> None: ...
    def send_key(self, key: str) -> None: ...


class WtypeBackend:
    def type_text(self, text: str) -> None:
        try:
            subprocess.run(["wtype", "--", text], check=True, timeout=10)
        except FileNotFoundError:
            print("wtype not found — install it for keyboard injection", file=sys.stderr)
        except subprocess.SubprocessError as e:
            print(f"wtype error: {e}", file=sys.stderr)

    def send_key(self, key: str) -> None:
        try:
            subprocess.run(["wtype", "-k", key], check=True, timeout=10)
        except FileNotFoundError:
            print("wtype not found — install it for keyboard injection", file=sys.stderr)
        except subprocess.SubprocessError as e:
            print(f"wtype error: {e}", file=sys.stderr)


class PrintBackend:
    def type_text(self, text: str) -> None:
        print(text, end="", flush=True)

    def send_key(self, key: str) -> None:
        key_map = {"Return": "\n", "Tab": "\t", "BackSpace": "\b"}
        print(key_map.get(key, f"[{key}]"), end="", flush=True)
