#!/usr/bin/env python3
"""Your notes in the launcher: type a few words and the notes that have them all are listed,
with the line they're on. Choosing one opens it; "Search Notes for …" opens the folder.

A search provider speaking GNOME Shell's org.gnome.Shell.SearchProvider2, so the same program
serves BlueRune's launcher and GNOME's overview. It reads the .md, .txt and .org files in
$BLUERUNE_NOTES_DIR, or ~/Notes. The session bus starts it when a search needs it, and it
leaves after five idle minutes. With --open it opens the notes folder: what its app entry does.

Needs Python's GLib bindings (python-gobject on Arch). See docs/extensions.md.
"""

import os
import sys

import gi

gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib  # noqa: E402

NAME = "org.bluerune.NotesSearch"
PATH = "/org/bluerune/NotesSearch"
# Leaves after this many seconds without a call; the bus starts it again when needed.
IDLE = 300
ENDINGS = (".md", ".txt", ".org")
# What is read of one note, and how many notes at most: a search answers in a moment.
MAX_BYTES = 256 * 1024
MAX_NOTES = 5000
MAX_RESULTS = 100
# The characters of the matching line shown under a note's title.
SNIPPET = 90

INTERFACE = """
<node>
  <interface name="org.gnome.Shell.SearchProvider2">
    <method name="GetInitialResultSet">
      <arg type="as" name="terms" direction="in"/>
      <arg type="as" name="results" direction="out"/>
    </method>
    <method name="GetSubsearchResultSet">
      <arg type="as" name="previous_results" direction="in"/>
      <arg type="as" name="terms" direction="in"/>
      <arg type="as" name="results" direction="out"/>
    </method>
    <method name="GetResultMetas">
      <arg type="as" name="identifiers" direction="in"/>
      <arg type="aa{sv}" name="metas" direction="out"/>
    </method>
    <method name="ActivateResult">
      <arg type="s" name="identifier" direction="in"/>
      <arg type="as" name="terms" direction="in"/>
      <arg type="u" name="timestamp" direction="in"/>
    </method>
    <method name="LaunchSearch">
      <arg type="as" name="terms" direction="in"/>
      <arg type="u" name="timestamp" direction="in"/>
    </method>
  </interface>
</node>
"""


def folder():
    return os.path.realpath(os.path.expanduser(os.environ.get("BLUERUNE_NOTES_DIR") or "~/Notes"))


def open_uri(uri):
    try:
        Gio.AppInfo.launch_default_for_uri(uri, None)
    except GLib.Error as error:
        print(f"can't open {uri}: {error.message}", file=sys.stderr)


class Note:
    def __init__(self, path, stamp, text):
        self.stamp = stamp
        lines = [line.strip() for line in text.splitlines()]
        first = next((line for line in lines if line), "")
        # A Markdown or Org heading's marks aren't part of the title.
        self.title = first.lstrip("#* ").strip() or os.path.splitext(os.path.basename(path))[0]
        self.lines = [line for line in lines if line]
        # The file's name counts too: "garden" finds Garden.txt whatever its first line says.
        self.folded = (os.path.splitext(os.path.basename(path))[0] + "\n" + text).casefold()

    def has(self, terms):
        return all(term in self.folded or term in self.title.casefold() for term in terms)

    def snippet(self, terms):
        """The first line after the title with one of the words, else the second line."""
        body = self.lines[1:]
        line = next((line for line in body if any(term in line.casefold() for term in terms)), body[0] if body else "")
        return line if len(line) <= SNIPPET else line[: SNIPPET - 1] + "…"


class Notes:
    def __init__(self):
        self.read = {}  # path -> Note, read again when the file changes
        self.terms = []

    def scan(self):
        root, seen = folder(), set()
        for directory, subdirectories, files in os.walk(root):
            subdirectories[:] = [name for name in subdirectories if not name.startswith(".")]
            for name in files:
                if len(seen) >= MAX_NOTES:
                    break
                if name.startswith(".") or not name.endswith(ENDINGS):
                    continue
                path = os.path.join(directory, name)
                try:
                    stamp = os.stat(path).st_mtime
                    if path not in self.read or self.read[path].stamp != stamp:
                        with open(path, "rb") as file:
                            self.read[path] = Note(path, stamp, file.read(MAX_BYTES).decode("utf-8", "replace"))
                except OSError:
                    continue
                seen.add(path)
        for gone in set(self.read) - seen:
            del self.read[gone]
        return root

    def note(self, identifier):
        """The note an id names: a path inside the notes folder, never outside it."""
        path = os.path.realpath(os.path.join(folder(), identifier))
        return self.read.get(path) if path.startswith(folder() + os.sep) else None

    def search(self, terms):
        self.terms = [term.casefold() for term in terms]
        root = self.scan()
        found = [(path, note) for path, note in self.read.items() if note.has(self.terms)]
        # Titles with the words first, then the newest.
        found.sort(key=lambda item: (not all(term in item[1].title.casefold() for term in self.terms), -item[1].stamp))
        return [os.path.relpath(path, root) for path, _ in found[:MAX_RESULTS]]

    def narrow(self, previous, terms):
        self.terms = [term.casefold() for term in terms]
        return [identifier for identifier in previous if (note := self.note(identifier)) and note.has(self.terms)]

    def metas(self, identifiers):
        icon = Gio.ThemedIcon.new("text-x-generic").serialize()
        metas = []
        for identifier in identifiers:
            note = self.note(identifier)
            if note:
                metas.append({"id": GLib.Variant("s", identifier), "name": GLib.Variant("s", note.title), "description": GLib.Variant("s", note.snippet(self.terms)), "icon": icon})
        return metas


class Provider:
    def __init__(self, loop):
        self.loop = loop
        self.notes = Notes()
        self.idle = None
        self.rest()

    def rest(self):
        """Leaves after IDLE seconds unless called again."""
        if self.idle:
            GLib.source_remove(self.idle)
        self.idle = GLib.timeout_add_seconds(IDLE, self.loop.quit)

    def called(self, connection, sender, path, interface, method, args, invocation):
        self.rest()
        args = args.unpack()
        if method == "GetInitialResultSet":
            invocation.return_value(GLib.Variant("(as)", (self.notes.search(args[0]),)))
        elif method == "GetSubsearchResultSet":
            invocation.return_value(GLib.Variant("(as)", (self.notes.narrow(args[0], args[1]),)))
        elif method == "GetResultMetas":
            invocation.return_value(GLib.Variant("(aa{sv})", (self.notes.metas(args[0]),)))
        elif method == "ActivateResult":
            note = self.notes.note(args[0])
            if note:
                open_uri(Gio.File.new_for_path(os.path.join(folder(), args[0])).get_uri())
            invocation.return_value(None)
        elif method == "LaunchSearch":
            open_uri(Gio.File.new_for_path(folder()).get_uri())
            invocation.return_value(None)


def main():
    if "--open" in sys.argv[1:]:
        os.makedirs(folder(), exist_ok=True)
        open_uri(Gio.File.new_for_path(folder()).get_uri())
        return
    loop = GLib.MainLoop()
    provider = Provider(loop)
    node = Gio.DBusNodeInfo.new_for_xml(INTERFACE)

    def acquired(connection, name):
        connection.register_object(PATH, node.interfaces[0], provider.called, None, None)

    Gio.bus_own_name(Gio.BusType.SESSION, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lambda *_: loop.quit())
    loop.run()


if __name__ == "__main__":
    main()
