#!/usr/bin/env python3
"""Typeless VoiceIME: IBus engine that commits UTF-8 from input-helper.

IBus engines must be a separate process. libInputHelper.so lives inside
Electron and must not pump GLib's default context or link libibus. This
process owns the GLib loop, registers as `typeless-voice`, and exposes a
Unix socket so input-helper / linux-shared can commit text and read
first-party focus + password state.

Launch modes:
  --xml   print a bare <engines> block and exit (ibus write-cache)
  --ibus  spawned by ibus-daemon; only request the D-Bus name
  (none)  spawned by input-helper; register_component at runtime
"""

from __future__ import annotations

import json
import os
import shlex
import signal
import sys
import threading
import time

SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIRECTORY not in sys.path:
    sys.path.insert(0, SCRIPT_DIRECTORY)

from voice_ime_protocol import (  # noqa: E402
    BINARY_NAME,
    COMPONENT_NAME,
    COMMIT_TIMEOUT_SECONDS,
    ENGINE_NAME,
    ENGINE_RANK,
    FOCUS_TIMEOUT_SECONDS,
    MAX_PAYLOAD_BYTES,
    REPLY_ERROR,
    REPLY_NO_ENGINE,
    REPLY_NO_FOCUS,
    REPLY_OK,
    REPLY_PASSWORD_EDITABLE,
    REPLY_PASSWORD_FOCUSED,
    REPLY_TIMEOUT,
    selected_slice,
    status_token,
)
from voice_ime_socket_server import (  # noqa: E402
    VoiceImeSocketServer,
    socket_path,
)

try:
    import gi

    gi.require_version("IBus", "1.0")
    from gi.repository import GLib, IBus
except (ImportError, ValueError) as import_error:
    sys.stderr.write(
        "typeless-voice-ime: python3-gi / gir1.2-ibus-1.0 required: "
        f"{import_error}\n"
    )
    sys.exit(1)


def _install_parent_death_signal() -> None:
    """Ask the kernel to SIGTERM this process when the spawner exits."""
    try:
        import ctypes

        libc = ctypes.CDLL("libc.so.6", use_errno=True)
        pr_set_pdeathsig = 1
        libc.prctl(pr_set_pdeathsig, signal.SIGTERM)
    except OSError:
        return


class VoiceImeEngine(IBus.Engine):
    __gtype_name__ = "TypelessVoiceImeEngine"

    def __init__(self):
        super().__init__()
        self._lock = threading.Lock()
        self._enabled = False
        # focus_in = 这个 IM context 拿到键盘焦点，≠ 控件可编辑。
        # GTK/Chromium 常在窗口级就 FocusIn。可编辑看 content-type /
        # surrounding-text：GTK Entry 在 focus_in 后会 SetContentType 并响应
        # retrieve-surrounding；纯 frame/按钮通常两者都不发。
        self._keyboard_focused = False
        self._has_surrounding = False
        self._has_content_type = False
        self._password = False
        self._surrounding_text = ""
        self._cursor = 0
        self._anchor = 0
        self._surrounding_generation = 0
        # toolkit 能力位，不是可编辑证据。GTK IM module 常把
        # SURROUNDING_TEXT 打在窗口级 context 上。
        self._client_capabilities = 0

    def _invalidate_context_locked(self):
        # 换控件后旧 surrounding 立刻失效；generation 让读侧丢弃快照。
        self._has_surrounding = False
        self._has_content_type = False
        self._password = False
        self._surrounding_text = ""
        self._cursor = 0
        self._anchor = 0
        self._client_capabilities = 0
        self._surrounding_generation += 1

    def _clear_focus_locked(self):
        self._keyboard_focused = False
        self._invalidate_context_locked()

    def _request_surrounding(self):
        # 很多应用只有引擎先要才会 SetSurroundingText（与 GTK
        # retrieve-surrounding / ibus_engine_get_surrounding_text 一致）。
        # Ubuntu 22.04 是 IBus 1.5.26，没有 construct 期
        # active-surrounding-text；enable/focus_in/reset 里调用在 24/26
        # 仍然有效。不要用返回值，那是引擎私有缓存。
        try:
            self.get_surrounding_text()
        except (TypeError, AttributeError, RuntimeError):
            return

    def _has_editable_evidence_locked(self):
        # 不看 _client_capabilities：IBUS_CAP_SURROUNDING_TEXT 不是
        # 「当前控件可打字」，Chromium/终端也曾被报成常开。
        return self._has_surrounding or self._has_content_type

    def _is_editable_locked(self):
        # 密码 / 非密码同一套：键盘焦点且有 surrounding 或 content-type。
        if not self._keyboard_focused:
            return False
        return self._has_editable_evidence_locked()

    def do_enable(self):
        with self._lock:
            self._enabled = True
        SERVICE.attach_engine(self)
        self._request_surrounding()

    def do_disable(self):
        # IBus 切窗口时会 disable；实例留下，可编辑证据在 focus_out 清。
        return

    def do_focus_in(self):
        with self._lock:
            self._keyboard_focused = True
            self._invalidate_context_locked()
        SERVICE.attach_engine(self)
        self._request_surrounding()

    def do_focus_out(self):
        with self._lock:
            self._clear_focus_locked()

    def do_reset(self):
        # 鼠标点走 caret、Enter/方向键、组合键打断时 daemon 会 Reset。
        # 不是 focus_out：可编辑证据留下。Wayland/GTK3 鼠标挪光标常常
        # 不推 SurroundingText（ibus#2765），再要一次补偿。
        self._request_surrounding()

    def do_set_capabilities(self, caps):
        # 客户端 toolkit 能力，不是「当前控件可编辑」。
        # IBUS_CAP_SURROUNDING_TEXT = 1<<3，常在窗口级 IM context 上常开。
        try:
            capability_bits = int(caps)
        except (TypeError, ValueError):
            capability_bits = 0
        with self._lock:
            self._client_capabilities = capability_bits

    def do_set_cursor_location(self, x, y, w, h):
        # 候选框矩形。不要在这里 RequireSurroundingText（D-Bus）。
        return

    def do_set_surrounding_text(self, text, cursor_pos, anchor_pos):
        # 客户端响应了 surrounding 协议。空串也算：控件在推 caret。
        # 不把正文写进日志。先 chain-up，否则 IBusEngine 私有缓存不更新，
        # 之后 get_surrounding_text() / delete_surrounding_text 会对不齐。
        try:
            IBus.Engine.do_set_surrounding_text(
                self, text, cursor_pos, anchor_pos
            )
        except (TypeError, AttributeError):
            pass

        surrounding = ""
        try:
            if text is not None and hasattr(text, "get_text"):
                surrounding = text.get_text() or ""
                # selected_slice 用 len/切片按码点；GI 偶发 bytes 时
                # len 会变成字节数，必须先 decode。
                if not isinstance(surrounding, str):
                    surrounding = surrounding.decode("utf-8", "replace")
        except (TypeError, AttributeError, RuntimeError, UnicodeDecodeError):
            surrounding = ""

        # IBus cursor/anchor 是 Unicode 码点下标，与 Python 3 str 一致。
        character_count = len(surrounding)
        try:
            cursor = int(cursor_pos)
        except (TypeError, ValueError):
            cursor = 0
        try:
            anchor = int(anchor_pos)
        except (TypeError, ValueError):
            anchor = cursor
        if cursor < 0:
            cursor = 0
        elif cursor > character_count:
            cursor = character_count
        if anchor < 0:
            anchor = 0
        elif anchor > character_count:
            anchor = character_count

        with self._lock:
            self._has_surrounding = True
            self._surrounding_text = surrounding
            self._cursor = cursor
            self._anchor = anchor
            self._surrounding_generation += 1

    def do_set_content_type(self, purpose, hints):
        password = False
        try:
            if purpose in (
                IBus.InputPurpose.PASSWORD,
                IBus.InputPurpose.PIN,
            ):
                password = True
            private_hint = int(IBus.InputHints.PRIVATE)
            sensitive_hint = int(
                getattr(IBus.InputHints, "SENSITIVE", 0) or 0
            )
            if int(hints) & (private_hint | sensitive_hint):
                password = True
        except (TypeError, ValueError, AttributeError):
            password = False
        with self._lock:
            self._has_content_type = True
            self._password = password

    def do_process_key_event(self, keyval, keycode, state):
        # Transparent: never consume physical keystrokes.
        # VoiceIME 只 commit 转写，不走组字；Ctrl/Alt 组合放行给应用。
        return False

    def snapshot(self):
        with self._lock:
            return {
                "enabled": self._enabled,
                "keyboard_focused": self._keyboard_focused,
                "editable": self._is_editable_locked(),
                "has_editable_evidence": self._has_editable_evidence_locked(),
                "password": self._password,
                "surrounding_text": self._surrounding_text,
                "cursor": self._cursor,
                "anchor": self._anchor,
                "surrounding_generation": self._surrounding_generation,
                "client_capabilities": self._client_capabilities,
            }

    def status_token(self) -> str:
        snap = self.snapshot()
        return status_token(
            snap["keyboard_focused"],
            snap["has_editable_evidence"],
            snap["password"],
        )

    def surrounding_json(self) -> str:
        snap = self.snapshot()
        if not snap["keyboard_focused"]:
            return REPLY_NO_FOCUS
        # 密码框通常不推 surrounding；即使有也不把选区交给业务。
        # selected_slice 不感知密码：这里先清空 text，或不调用。
        selected = ""
        text = snap["surrounding_text"]
        cursor = snap["cursor"]
        anchor = snap["anchor"]
        if snap["password"]:
            text = ""
            cursor = 0
            anchor = 0
        else:
            selected = selected_slice(text, cursor, anchor)
        payload = json.dumps(
            {
                "ok": True,
                "text": text,
                "cursor": cursor,
                "anchor": anchor,
                "selected": selected,
                "password": snap["password"],
            },
            ensure_ascii=False,
            separators=(",", ":"),
        )
        encoded = payload.encode("utf-8")
        if len(encoded) > MAX_PAYLOAD_BYTES:
            return REPLY_ERROR
        return payload

    def commit_on_main_loop(self, text: str) -> str:
        snap = self.snapshot()
        if snap["password"]:
            return (
                REPLY_PASSWORD_EDITABLE
                if snap["has_editable_evidence"]
                else REPLY_PASSWORD_FOCUSED
            )
        if not snap["editable"]:
            return REPLY_NO_FOCUS
        if not text:
            return REPLY_ERROR

        outcome = {"reply": REPLY_TIMEOUT}
        finished = threading.Event()

        def idle_commit():
            try:
                snap_now = self.snapshot()
                if snap_now["password"]:
                    outcome["reply"] = (
                        REPLY_PASSWORD_EDITABLE
                        if snap_now["has_editable_evidence"]
                        else REPLY_PASSWORD_FOCUSED
                    )
                elif not snap_now["editable"]:
                    outcome["reply"] = REPLY_NO_FOCUS
                else:
                    self.commit_text(IBus.Text.new_from_string(text))
                    outcome["reply"] = REPLY_OK
            except Exception:
                outcome["reply"] = REPLY_ERROR
            finished.set()
            return False

        GLib.idle_add(idle_commit)
        if not finished.wait(COMMIT_TIMEOUT_SECONDS):
            return REPLY_TIMEOUT
        return outcome["reply"]


class VoiceImeService:
    def __init__(self):
        self._engine_lock = threading.Lock()
        self._engine = None
        self._server = VoiceImeSocketServer(
            status_provider=self.status_reply,
            commit_handler=self.commit_from_socket,
            surrounding_provider=self.surrounding_reply,
        )

    def start_socket(self) -> bool:
        return self._server.start()

    def stop_socket(self) -> None:
        self._server.stop()

    def attach_engine(self, engine: VoiceImeEngine) -> None:
        with self._engine_lock:
            self._engine = engine

    def status_reply(self) -> str:
        with self._engine_lock:
            engine = self._engine
        if engine is None:
            return REPLY_NO_ENGINE
        return engine.status_token()

    def surrounding_reply(self) -> str:
        with self._engine_lock:
            engine = self._engine
        if engine is None:
            return REPLY_NO_ENGINE
        # 选区可能在 focus_in 之后才变；在 GLib 主循环 retrieve-surrounding，
        # 等一次 SetSurroundingText 刷新 cursor/anchor。
        snap = engine.snapshot()
        generation = snap["surrounding_generation"]

        def idle_request():
            engine._request_surrounding()
            return False

        GLib.idle_add(idle_request)
        deadline = time.monotonic() + 0.15
        while time.monotonic() < deadline:
            snap = engine.snapshot()
            if snap["surrounding_generation"] != generation:
                break
            if not snap["keyboard_focused"]:
                break
            time.sleep(0.02)
        return engine.surrounding_json()

    def commit_from_socket(self, text: str) -> str:
        with self._engine_lock:
            engine = self._engine
        if engine is None:
            return REPLY_NO_ENGINE
        # surrounding / content-type 在 FocusIn 之后异步到达；不要用
        # 单纯键盘焦点当可编辑。
        deadline = time.monotonic() + FOCUS_TIMEOUT_SECONDS
        while True:
            snap = engine.snapshot()
            if snap["password"]:
                return (
                    REPLY_PASSWORD_EDITABLE
                    if snap["has_editable_evidence"]
                    else REPLY_PASSWORD_FOCUSED
                )
            if snap["editable"]:
                return engine.commit_on_main_loop(text)
            if time.monotonic() >= deadline:
                return REPLY_NO_FOCUS
            time.sleep(0.05)


SERVICE = VoiceImeService()


def print_engine_xml() -> None:
    sys.stdout.write(
        "<engines>\n"
        "  <engine>\n"
        f"    <name>{ENGINE_NAME}</name>\n"
        "    <longname>Typeless Voice IME</longname>\n"
        "    <description>Commit speech-to-text into the focused input context</description>\n"
        "    <language>other</language>\n"
        "    <license>MIT</license>\n"
        "    <author>Typeless</author>\n"
        "    <icon>audio-input-microphone</icon>\n"
        "    <layout>default</layout>\n"
        f"    <rank>{ENGINE_RANK}</rank>\n"
        "  </engine>\n"
        "</engines>\n"
    )


def _executable_path() -> str:
    try:
        return os.readlink("/proc/self/exe")
    except OSError:
        return os.path.abspath(sys.argv[0] if sys.argv else BINARY_NAME)


def _ibus_exec_line() -> str:
    """Command ibus-daemon should spawn for this engine.

    extraResources 常把入口打成 644，native_child 会用 `python3 script` 拉起。
    此时 /proc/self/exe 是解释器，不能注册成 `python3 --ibus`。
    """
    script_path = os.path.abspath(sys.argv[0] if sys.argv else BINARY_NAME)
    if os.path.isfile(script_path) and os.access(script_path, os.X_OK):
        return f"{shlex.quote(script_path)} --ibus"
    if os.path.isfile(script_path):
        python_path = sys.executable or "python3"
        return f"{shlex.quote(python_path)} {shlex.quote(script_path)} --ibus"
    return f"{shlex.quote(_executable_path())} --ibus"


def _run_glib_loop(bus=None, factory=None) -> int:
    main_loop = GLib.MainLoop()

    def quit_loop(*_unused):
        SERVICE.stop_socket()
        main_loop.quit()
        return False

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, quit_loop)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, quit_loop)
    if bus is not None:
        bus.connect("disconnected", lambda *_args: quit_loop())
    try:
        main_loop.run()
    finally:
        SERVICE.stop_socket()
        del factory
    return 0


def main() -> int:
    if len(sys.argv) > 1 and sys.argv[1] == "--xml":
        print_engine_xml()
        return 0

    spawned_by_ibus = len(sys.argv) > 1 and sys.argv[1] == "--ibus"
    if not spawned_by_ibus:
        _install_parent_death_signal()

    # 先听 socket，再连 IBus。否则 native_child 的 1s 等待会在 IBus.init 上超时，
    # 进程看起来像从未启动。
    if not SERVICE.start_socket():
        sys.stderr.write("typeless-voice-ime: listen socket failed\n")
        return 1
    sys.stderr.write(
        f"typeless-voice-ime: listening pid={os.getpid()} "
        f"socket={socket_path()}\n"
    )

    IBus.init()
    bus = IBus.Bus()
    if not bus.is_connected():
        sys.stderr.write(
            "typeless-voice-ime: cannot connect to IBus; socket stays up\n"
        )
        return _run_glib_loop()

    factory = IBus.Factory.new(bus.get_connection())
    factory.add_engine(ENGINE_NAME, VoiceImeEngine)
    if spawned_by_ibus:
        bus.request_name(COMPONENT_NAME, 0)
    else:
        exec_line = _ibus_exec_line()
        component = IBus.Component.new(
            COMPONENT_NAME,
            "Typeless Voice IME",
            "1.0",
            "MIT",
            "Typeless",
            "https://typeless.ai",
            exec_line,
            "typeless",
        )
        description = IBus.EngineDesc.new(
            ENGINE_NAME,
            "Typeless Voice IME",
            "Commit speech-to-text into the focused input context",
            "other",
            "MIT",
            "Typeless",
            "audio-input-microphone",
            "default",
        )
        try:
            description.set_property("rank", ENGINE_RANK)
        except TypeError:
            pass
        component.add_engine(description)
        bus.register_component(component)

    sys.stderr.write(
        f"typeless-voice-ime: registered IBus engine {ENGINE_NAME} "
        f"component={COMPONENT_NAME}\n"
    )
    return _run_glib_loop(bus, factory)


if __name__ == "__main__":
    sys.exit(main())
