#!/usr/bin/env python3
"""labwc-appmenu: erzeugt aus installierten .desktop-Dateien ein
labwc-Pipe-Menue ("Alle Anwendungen").

Wird bei jedem Oeffnen des Root-Menues frisch aufgerufen (labwc cacht
Pipe-Menues nur, solange das Menue offen ist) - neu installierte Apps
(Brave/Bazaar per Flatpak eingeschlossen) erscheinen daher von selbst.

- Deutsche Namen via Name[de], sonst Name
- Kategorien nach Freedesktop-Mapping, Rest unter "Sonstige"
- NoDisplay/Hidden sowie fehlende TryExec-Binaries werden uebersprungen
- Terminal-Apps (Terminal=true) starten in gnome-terminal
- Keine Abhaengigkeiten ausser Python3-Standardlib
"""
import configparser
import os
import re
import shlex
import shutil
import sys
import xml.sax.saxutils as sax

def esc(value):
    # sax.escape maskiert standardmaessig nur <, >, &. Fuer Attributwerte
    # (doppelte Anfuehrungszeichen) zusaetzlich " maskieren, damit Namen/
    # Icons mit Anfuehrungszeichen das Pipe-Menue nicht ungueltig machen.
    return sax.escape(str(value), {'"': '&quot;', "'": '&apos;'})

APP_DIRS = [
    os.path.expanduser("~/.local/share/flatpak/exports/share/applications"),
    "/var/lib/flatpak/exports/share/applications",
    os.path.expanduser("~/.local/share/applications"),
    "/usr/local/share/applications",
    "/usr/share/applications",
]

# Freedesktop-Hauptkategorien -> deutsche Rubriken (Reihenfolge = Anzeige)
SECTIONS = [
    ("AudioVideo", "Multimedia"),
    ("Development", "Entwicklung"),
    ("Education", "Bildung"),
    ("Game", "Spiele"),
    ("Graphics", "Grafik"),
    ("Network", "Internet"),
    ("Office", "Büro"),
    ("Science", "Wissenschaft"),
    ("Settings", "Einstellungen"),
    ("System", "System"),
    ("Utility", "Zubehör"),
]
FALLBACK_SECTION = "Sonstige"

# Feld-Codes aus Exec entfernen (%f %F %u %U %d %D %n %N %i %c %k %v %m)
FIELD_CODES = {
    "%f", "%F", "%u", "%U", "%d", "%D", "%n", "%N",
    "%i", "%c", "%k", "%v", "%m",
}


def clean_exec(exec_line):
    # shlex statt naive split (gequotete Pfade mit Leerzeichen bleiben ganz).
    # Exakte Field-Codes fliegen raus; angeklebte Reste (%U, etc.) werden
    # entfernt, leere Tokens gedroppt. Trade-off: ein legitimes "%f" als
    # Teil eines Arguments (praktisch inexistent in Exec-Zeilen) wuerde
    # mit entfernt - akzeptiert zugunsten robuster Menue-Commands.
    try:
        parts = shlex.split(exec_line)
    except ValueError:
        parts = exec_line.split()
    cleaned = []
    for p in parts:
        if p in FIELD_CODES:
            continue
        p = re.sub(r"%[fFuUdDnNickvm]", "", p)
        if p:
            cleaned.append(p)
    # shlex.join: Tokens mit Leerzeichen werden gequotet, damit labwc
    # (Execute laeuft ueber die Shell) sie wieder als ein Argument sieht.
    return shlex.join(cleaned).strip()


def read_desktop(path):
    parser = configparser.ConfigParser(strict=False, interpolation=None)
    parser.optionxform = str  # Schluessel case-sensitiv (Name[de]!)
    try:
        with open(path, encoding="utf-8", errors="replace") as handle:
            parser.read_file(handle)
    except OSError:
        return None
    if "Desktop Entry" not in parser:
        return None
    return parser["Desktop Entry"]


def main():
    seen = set()
    sections = {label: [] for _, label in SECTIONS}
    sections[FALLBACK_SECTION] = []

    for app_dir in APP_DIRS:
        try:
            files = sorted(os.listdir(app_dir))
        except OSError:
            continue
        for filename in files:
            if not filename.endswith(".desktop"):
                continue
            if filename in seen:
                continue
            seen.add(filename)
            entry = read_desktop(os.path.join(app_dir, filename))
            if entry is None:
                continue
            if entry.get("NoDisplay", "false").lower() == "true":
                continue
            if entry.get("Hidden", "false").lower() == "true":
                continue
            if entry.get("Type", "Application") != "Application":
                continue
            name = entry.get("Name[de]") or entry.get("Name")
            exec_line = entry.get("Exec")
            if not name or not exec_line:
                continue
            command = clean_exec(exec_line)
            if not command:
                continue
            try_exec = entry.get("TryExec")
            if try_exec and shutil.which(try_exec) is None:
                continue
            if entry.get("Terminal", "false").lower() == "true":
                command = "gnome-terminal -- " + command
            icon = entry.get("Icon", "")
            categories = entry.get("Categories", "")
            label = FALLBACK_SECTION
            for cat_id, cat_label in SECTIONS:
                if cat_id in categories.split(";"):
                    label = cat_label
                    break
            sections[label].append((name.casefold(), name, command, icon))

    out = ["<openbox_pipe_menu>"]
    for _, label in SECTIONS:
        items = sections[label]
        if not items:
            continue
        out.append('  <separator label="%s" />' % esc(label))
        for _, name, command, icon in sorted(items):
            if icon:
                out.append('  <item label="%s" icon="%s">' % (esc(name), esc(icon)))
            else:
                out.append('  <item label="%s">' % esc(name))
            out.append('    <action name="Execute" command="%s" />' % esc(command))
            out.append("  </item>")
    rest = sections[FALLBACK_SECTION]
    if rest:
        out.append('  <separator label="%s" />' % esc(FALLBACK_SECTION))
        for _, name, command, icon in sorted(rest):
            if icon:
                out.append('  <item label="%s" icon="%s">' % (esc(name), esc(icon)))
            else:
                out.append('  <item label="%s">' % esc(name))
            out.append('    <action name="Execute" command="%s" />' % esc(command))
            out.append("  </item>")
    out.append("</openbox_pipe_menu>")
    sys.stdout.write("\n".join(out) + "\n")
    return 0


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