#!/usr/bin/python3 -I
"""Relay a GNOME Shell shortcut to its opted-in Firefox native port."""

import json
import os
import struct
import sys
import uuid
from dataclasses import dataclass

from gi.repository import Gio, GLib


INTERFACE = "io.github.klondikemarlen.OmpSendContext.Firefox"
OBJECT_PATH = "/io/github/klondikemarlen/OmpSendContext/Firefox"
SHELL_NAME = "org.gnome.Shell"
BUS_DAEMON = "org.freedesktop.DBus"
BUS_DAEMON_PATH = "/org/freedesktop/DBus"
REQUEST_TIMEOUT_MS = 2000
MAX_FRAME_BYTES = 1024
FRAME_LENGTH = struct.Struct("=I")
REPLY_FIELDS = {"type", "id", "ok"}

INTERFACE_INFO = Gio.DBusNodeInfo.new_for_xml(f"""
<node>
  <interface name="{INTERFACE}">
    <method name="Prepare">
      <arg type="s" name="id" direction="in"/>
      <arg type="b" name="ready" direction="out"/>
    </method>
    <method name="Commit">
      <arg type="s" name="id" direction="in"/>
      <arg type="b" name="accepted" direction="out"/>
    </method>
  </interface>
</node>
""").interfaces[0]


def is_request_id(value):
    try:
        return str(uuid.UUID(value)) == value
    except ValueError:
        return False


def respond(invocation, ok):
    invocation.return_value(GLib.Variant("(b)", (ok,)))


@dataclass
class PendingRequest:
    invocation: Gio.DBusMethodInvocation
    sender: str
    request_id: str
    reply_type: str
    deadline_us: int
    timeout_source: int


class DesktopConnector:
    def __init__(self, connection):
        self.connection = connection
        self.loop = GLib.MainLoop()
        self.input_buffer = bytearray()
        self.pending = None
        self.prepared = None
        # Shell generates one UUID per press; keep consumed IDs for this port's lifetime.
        self.seen_requests = set()
        self.exit_code = 0

    def run(self):
        os.set_blocking(0, False)
        os.set_blocking(1, False)
        self.connection.register_object(OBJECT_PATH, INTERFACE_INFO, self.on_method_call)
        self.own_connection_name()
        GLib.io_add_watch(
            GLib.IOChannel.unix_new(0),
            GLib.PRIORITY_DEFAULT,
            GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR | GLib.IO_NVAL,
            self.on_browser_input,
        )
        self.loop.run()
        # Deliver any final false reply before the process drops its bus name.
        self.connection.flush_sync(None)
        return self.exit_code

    def own_connection_name(self):
        result = self.connection.call_sync(
            BUS_DAEMON, BUS_DAEMON_PATH, BUS_DAEMON, "RequestName",
            GLib.Variant("(su)", (f"{INTERFACE}.p{os.getpid()}", 4)),  # DO_NOT_QUEUE
            GLib.VariantType.new("(u)"), Gio.DBusCallFlags.NONE, 1000, None,
        )
        if result.unpack() != (1,):  # PRIMARY_OWNER
            raise RuntimeError("could not acquire the Firefox desktop connector name")

    def is_shell_owner(self, sender):
        try:
            owner = self.connection.call_sync(
                BUS_DAEMON, BUS_DAEMON_PATH, BUS_DAEMON, "GetNameOwner",
                GLib.Variant("(s)", (SHELL_NAME,)), GLib.VariantType.new("(s)"),
                Gio.DBusCallFlags.NONE, 250, None,
            )
        except GLib.Error:
            return False
        return owner.unpack() == (sender,)

    def on_method_call(self, _bus, sender, _path, _interface, method, parameters, invocation):
        if not self.is_shell_owner(sender):
            invocation.return_dbus_error(
                "org.freedesktop.DBus.Error.AccessDenied",
                "Only the current GNOME Shell owner may call this connector.",
            )
            return

        (request_id,) = parameters.unpack()
        if self.pending or not is_request_id(request_id):
            respond(invocation, False)
            return

        if method == "Prepare":
            if request_id in self.seen_requests:
                respond(invocation, False)
                return
            self.seen_requests.add(request_id)
            self.prepared = None
            reply_type = "prepared"
        else:
            if self.prepared != (sender, request_id):
                respond(invocation, False)
                return
            self.prepared = None
            reply_type = "committed"

        self.pending = PendingRequest(
            invocation, sender, request_id, reply_type,
            GLib.get_monotonic_time() + REQUEST_TIMEOUT_MS * 1000,
            GLib.timeout_add(REQUEST_TIMEOUT_MS, self.on_timeout),
        )
        message = json.dumps({"type": method.lower(), "id": request_id}).encode("utf-8")
        frame = FRAME_LENGTH.pack(len(message)) + message
        try:
            if os.write(1, frame) == len(frame):
                return
        except OSError:
            pass
        self.stop(exit_code=1)

    def on_browser_input(self, _channel, condition):
        if condition & (GLib.IO_HUP | GLib.IO_ERR | GLib.IO_NVAL):
            return self.stop()

        try:
            chunk = os.read(0, 4096)
        except OSError:
            return self.stop(exit_code=1)
        if not chunk:
            return self.stop()

        self.input_buffer.extend(chunk)
        while len(self.input_buffer) >= FRAME_LENGTH.size:
            (length,) = FRAME_LENGTH.unpack_from(self.input_buffer)
            if not 0 < length <= MAX_FRAME_BYTES:
                return self.stop(exit_code=1)
            frame_end = FRAME_LENGTH.size + length
            if len(self.input_buffer) < frame_end:
                break

            try:
                reply = json.loads(self.input_buffer[FRAME_LENGTH.size:frame_end].decode("utf-8"))
            except (ValueError, RecursionError):
                return self.stop(exit_code=1)
            del self.input_buffer[:frame_end]
            if not self.on_browser_reply(reply):
                return GLib.SOURCE_REMOVE
        return GLib.SOURCE_CONTINUE

    def on_browser_reply(self, reply):
        pending = self.pending
        if not pending:
            return GLib.SOURCE_CONTINUE
        if GLib.get_monotonic_time() >= pending.deadline_us:
            return self.stop(exit_code=1)
        if (
            not isinstance(reply, dict)
            or reply.keys() != REPLY_FIELDS
            or reply["type"] != pending.reply_type
            or reply["id"] != pending.request_id
            or not isinstance(reply["ok"], bool)
        ):
            return GLib.SOURCE_CONTINUE

        if pending.reply_type == "prepared" and reply["ok"]:
            self.prepared = (pending.sender, pending.request_id)
        self.finish_request(reply["ok"])
        return GLib.SOURCE_CONTINUE

    def finish_request(self, ok):
        pending = self.pending
        self.pending = None
        if pending.timeout_source is not None:
            GLib.source_remove(pending.timeout_source)
        respond(pending.invocation, ok)

    def on_timeout(self):
        self.pending.timeout_source = None
        return self.stop(exit_code=1)

    def stop(self, *, exit_code=0):
        if self.pending:
            self.finish_request(False)
        self.exit_code = exit_code
        self.loop.quit()
        return GLib.SOURCE_REMOVE


def main():
    try:
        connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        return DesktopConnector(connection).run()
    except (GLib.Error, OSError, RuntimeError) as error:
        print(f"Firefox desktop connector: {error}", file=sys.stderr)
        return 1


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