Description: <short summary of the patch>
 TODO: Put a short summary on the line above and replace this paragraph
 with a longer explanation of this change. Complete the meta-information
 with other relevant fields (see below for details). To make it easier, the
 information below has been extracted from the changelog. Adjust it or drop
 it.
 .
 asus-screen-toggle (1.0.0-1) unstable; urgency=medium
 .
   * [NEW] Kompletní přepis User Agenta do Pythonu (Gtk + AppIndicator).
   * [NEW] Interaktivní menu v systray s možností manuálního přepínání režimů:
       - Automaticky (podle senzorů)
       - Vynuceno: Jen hlavní displej
       - Vynuceno: Oba displeje (Desktop)
   * [NEW] Perzistence nastavení: Agent si pamatuje zvolený režim i po restartu.
   * [NEW] Moderní SVG ikony indikující aktuální stav v liště.
   * [ARCH] Přechod z XDG Autostart na Systemd User Unit
       - (asus-user-agent.service).
   * [ARCH] Implementace D-Bus rozhraní (org.asus.ScreenToggle) pro komunikaci.
   * [FIX] Self-healing launcher: Automatická oprava služby při spuštění z menu.
   * [FIX] Vylepšená detekce grafického sezení (graphical-session.target).
Author: Antonin Micka <antonin.micka@gmail.com>

---
The information above should follow the Patch Tagging Guidelines, please
checkout https://dep.debian.net/deps/dep3/ to learn about the format. Here
are templates for supplementary fields that you might want to add:

Origin: (upstream|backport|vendor|other), (<patch-url>|commit:<commit-id>)
Bug: <upstream-bugtracker-url>
Bug-Debian: https://bugs.debian.org/<bugnumber>
Bug-Ubuntu: https://launchpad.net/bugs/<bugnumber>
Forwarded: (no|not-needed|<patch-forwarded-url>)
Applied-Upstream: <version>, (<commit-url>|commit:<commid-id>)
Reviewed-By: <name and email of someone who approved/reviewed the patch>
Last-Update: 2025-12-26

--- asus-screen-toggle-1.0.0.orig/asus-screen-toggle/usr/bin/asus-user-agent.py
+++ asus-screen-toggle-1.0.0/asus-screen-toggle/usr/bin/asus-user-agent.py
@@ -1,83 +1,75 @@
 #!/usr/bin/env python3
-"""
-Asus Screen Toggle User Agent
-Sleduje stav klávesnice a spravuje ikonu v oznamovací oblasti.
-"""
-
 import sys
 import os
 import signal
 import subprocess
 import warnings
+import time # Nový import pro čas
 import gettext
 import locale
-import shutil
-from pydbus.generic import signal as Signal
-
-# --- Globální nastavení ---
-DEBUG = False  # Pro vývoj nastavte na True
 
-def debug_log(message):
-    """Tiskne ladicí zprávy pouze pokud je aktivní DEBUG režim."""
-    if DEBUG:
-        print(f"DEBUG: {message}")
-
-# --- Lokalizace ---
+# Nastavení lokalizace
 APP_NAME = "asus-screen-toggle"
 LOCALE_DIR = "/usr/share/locale"
 
 try:
+    # Pokusíme se nastavit systémovou locale
     locale.setlocale(locale.LC_ALL, '')
+
+    # Inicializace gettext
     gettext.bindtextdomain(APP_NAME, LOCALE_DIR)
     gettext.textdomain(APP_NAME)
     _ = gettext.gettext
 except Exception as e:
-    debug_log(f"Localization failed to load: {e}")
+    # Fallback, pokud gettext selže (např. při vývoji mimo instalaci)
+    print(f"Warning: Localization not loaded: {e}")
     _ = lambda s: s
 
 warnings.filterwarnings("ignore")
+from pydbus.generic import signal as Signal
 
-# --- Importy GUI knihoven ---
+# --- Importy knihoven ---
+print(_("DEBUG: Načítám knihovny..."))
 try:
     import gi
-    gi.require_version('Gtk', '3.0')
-    from gi.repository import GLib, Gtk
-    from pydbus import SessionBus
-
-    # Detekce AppIndicatoru (Ayatana vs Standard)
     try:
         gi.require_version('AyatanaAppIndicator3', '0.1')
         from gi.repository import AyatanaAppIndicator3 as AppIndicator
     except (ValueError, ImportError):
-        gi.require_version('AppIndicator3', '0.1')
-        from gi.repository import AppIndicator3 as AppIndicator
+        try:
+            gi.require_version('AppIndicator3', '0.1')
+            from gi.repository import AppIndicator3 as AppIndicator
+        except (ValueError, ImportError):
+            print(_("CHYBA: Nenalezena knihovna AppIndicator."))
+            sys.exit(1)
+
+    gi.require_version('Gtk', '3.0')
+    from gi.repository import GLib, Gtk
+    from pydbus import SessionBus
 except Exception as e:
-    sys.stderr.write(f"FATAL: Required libraries missing: {e}\n")
+    print(f_("CHYBA při importu knihoven: {e}"))
     sys.exit(1)
 
-# --- Konfigurace cest ---
+# --- Konfigurace ---
 BUS_NAME = "org.asus.ScreenToggle"
-SCRIPT_NAME = "asus-check-keyboard-user"
-SETTINGS_NAME = "asus-screen-settings"
+SCRIPT_PATH = "/usr/bin/asus-check-keyboard-user"
+APP_ID = "asus-screen-toggler"
+ICON_NAME = "input-tablet"
+ICON_PATH = "/usr/share/asus-screen-toggle"
 
-# Dynamické nalezení cest k binárkám
-SCRIPT_PATH = shutil.which(SCRIPT_NAME) or f"/usr/bin/{SCRIPT_NAME}"
-SETTINGS_PATH = shutil.which(SETTINGS_NAME) or f"/usr/bin/{SETTINGS_NAME}"
+ICON_AUTO_NAME = "icon-green.svg"
+ICON_PRIMARY_NAME = "icon-red.svg"
+ICON_DESKTOP_NAME = "icon-blue.svg"
+ICON_AUTO = os.path.join(ICON_PATH, ICON_AUTO_NAME)
+ICON_PRIMARY = os.path.join(ICON_PATH, ICON_PRIMARY_NAME)
+ICON_DESKTOP = os.path.join(ICON_PATH, ICON_DESKTOP_NAME)
 
-ICON_PATH = "/usr/share/asus-screen-toggle"
 STATE_DIR = os.path.expanduser("~/.local/state/asus-check-keyboard")
 STATE_FILE = os.path.join(STATE_DIR, "state")
-SYS_CONFIG = "/etc/asus-screen-toggle.conf"
-USER_CONFIG = os.path.expanduser("~/.config/asus-screen-toggle/user.conf")
-
-# Ikony
-ICON_AUTO_NAME = "icon-green"
-ICON_PRIMARY_NAME = "icon-red"
-ICON_DESKTOP_NAME = "icon-blue"
+CONFIG_FILE = os.path.expanduser("~/.config/asus-screen-toggle/config.conf")
 
 class StatusNotifierItem:
-    #Implementace org.kde.StatusNotifierItem pro lepší integraci s KDE Plasma.
-    ***
+    """
     <node>
       <interface name="org.kde.StatusNotifierItem">
         <property name="Category" type="s" access="read"/>
@@ -88,14 +80,28 @@ class StatusNotifierItem:
         <property name="IconThemePath" type="s" access="read"/>
         <property name="ItemIsMenu" type="b" access="read"/>
         <property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
-        <method name="Activate"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
-        <method name="ContextMenu"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
-        <method name="SecondaryActivate"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
-        <signal name="NewIcon"/><signal name="NewStatus"/><signal name="NewToolTip"/>
+
+        <method name="Activate">
+          <arg type="i" direction="in"/>
+          <arg type="i" direction="in"/>
+        </method>
+
+        <method name="ContextMenu">
+          <arg type="i" direction="in"/>
+          <arg type="i" direction="in"/>
+        </method>
+
+        <method name="SecondaryActivate">
+          <arg type="i" direction="in"/>
+          <arg type="i" direction="in"/>
+        </method>
+
+        <signal name="NewIcon"/>
+        <signal name="NewStatus"/>
+        <signal name="NewToolTip"/>
       </interface>
     </node>
-    ***
-
+    """
     NewIcon = Signal()
     NewStatus = Signal()
     NewToolTip = Signal()
@@ -120,25 +126,33 @@ class StatusNotifierItem:
     @property
     def ItemIsMenu(self): return False
     @property
+    def Menu(self): return "/StatusNotifierItem"
+    @property
     def ToolTip(self): return (self.icon_name, [], _("Asus Screen Toggle"), _(f"Režim: {self.agent.mode}"))
 
     def Activate(self, x, y):
+        """Levý klik (SNI): Spustí přímo nastavení."""
+        # Voláme pomocnou metodu agenta
         GLib.idle_add(self.agent._launch_settings)
 
     def ContextMenu(self, x, y):
-        GLib.idle_add(self.agent._show_gtk_menu)
+        GLib.idle_add(self.agent._show_gtk_menu, 3)
 
     def SecondaryActivate(self, x, y):
-        self.agent._run_check("Tray_MiddleClick")
+        self.agent._run_check("SNI_MiddleClick")
 
     def set_icon(self, name):
-        if self.icon_name != name:
-            self.icon_name = name
+        base_name = os.path.splitext(os.path.basename(name))[0]
+        if self.icon_name != base_name:
+            self.icon_name = base_name
             self.NewIcon()
             self.NewToolTip()
 
+    def set_status(self, status):
+        self.status = status
+        self.NewStatus()
+
 class AsusAgent:
-    # Hlavní logika agenta, správa D-Bus a stavu aplikace."""
     """
     <node>
       <interface name="org.asus.ScreenToggle">
@@ -154,107 +168,163 @@ class AsusAgent:
 
     def __init__(self, quit_callback, bus):
         self.quit_callback = quit_callback
-        self.bus = bus
         self.mode = self._load_mode()
         self.config = self._load_config()
+        self.bus = bus
         self.indicator = None
         self.tray_backend = None
+        self.menu = None
 
+        # Pro sledování změn souboru
         self.last_file_mtime = 0
         if os.path.exists(STATE_FILE):
             self.last_file_mtime = os.stat(STATE_FILE).st_mtime
 
-        # Inicializace Tray podle prostředí
-        if os.environ.get("XDG_CURRENT_DESKTOP", "").lower() == "kde":
+        if is_kde():
             try:
                 self._setup_sni()
             except Exception as e:
-                debug_log(f"SNI failed, using AppIndicator: {e}")
+                print(f_("SNI failed, fallback na AppIndicator: {e}"))
                 self._setup_appindicator()
+                self.tray_backend = "appindicator"
         else:
             self._setup_appindicator()
+            self.tray_backend = "appindicator"
 
+        # Timer pro sledování externích změn souboru (každé 2s)
         GLib.timeout_add_seconds(2, self._monitor_file_change)
 
+    # --- Konfigurace ---
     def _load_config(self):
-        """Načte konfiguraci s logikou AND (Systém & Uživatel)."""
+        """
+        Načte konfiguraci s prioritou:
+        1. Defaultní hodnoty (v kódu)
+        2. Systémová konfigurace (/etc/asus-screen-toggle.conf)
+        3. Uživatelská konfigurace (~/.config/asus-screen-toggle/config.conf)
+        """
+        # 1. Defaultní hodnoty
         cfg = {"enable_dbus": True, "enable_signal": True}
-        paths = [SYS_CONFIG, USER_CONFIG]
 
-        for path in paths:
+        # Seznam souborů v pořadí, jak se mají aplikovat (poslední vyhrává)
+        config_paths = [
+            "/etc/asus-screen-toggle.conf",
+            os.path.expanduser("~/.config/asus-screen-toggle/config.conf")
+        ]
+
+        for path in config_paths:
             if os.path.exists(path):
                 try:
-                    debug_log(f"Reading config: {path}")
+                    print(_(f"⚙️ Načítám soubor: {path}"))
                     with open(path, 'r') as f:
                         for line in f:
-                            line = line.strip()
-                            if "=" in line and not line.startswith("#"):
-                                key, val = line.split("=", 1)
-                                key = key.strip().upper()
-                                is_true = (val.strip().lower() == "true")
-                                if key in ["ENABLE_DBUS", "ENABLE_SIGNAL"]:
-                                    cfg[key.lower()] = is_true and cfg[key.lower()]
+                            if "=" in line and not line.strip().startswith("#"):
+                                key, val = line.strip().split("=", 1)
+                                if key.strip().upper() == "ENABLE_DBUS": cfg["enable_dbus"] = (val.strip().lower() == "true")
+                                if key.strip().upper() == "ENABLE_SIGNAL": cfg["enable_signal"] = (val.strip().lower() == "true")
                 except: pass
         return cfg
 
     def _monitor_file_change(self):
-        """Sleduje externí změny stavového souboru."""
+        """Kontroluje, zda se soubor nezměnil externě (např. přes GUI Settings)."""
         if os.path.exists(STATE_FILE):
             try:
                 mtime = os.stat(STATE_FILE).st_mtime
                 if mtime != self.last_file_mtime:
+                    # Soubor se změnil!
                     self.last_file_mtime = mtime
-                    new_mode = self._load_mode()
+                    new_mode = self._load_mode(silent=True)
                     if new_mode != self.mode:
-                        debug_log(f"External state change: {new_mode}")
+                        print(_(f"🔄 Detekována externí změna stavu -> {new_mode}"))
                         self.mode = new_mode
                         self._set_icon_by_mode()
+                        # Zde nespouštíme _run_check, protože předpokládáme,
+                        # že ten kdo soubor změnil (Settings App), už skript spustil nebo spustí.
+                        # Jen aktualizujeme ikonu.
             except: pass
-        return True
+        return True # Pokračovat v timeru
 
-    def _load_mode(self):
+    def _load_mode(self, silent=False):
         if os.path.exists(STATE_FILE):
             try:
                 with open(STATE_FILE, 'r') as f:
                     mode = f.read().strip()
                     if mode in ["automatic-enabled", "enforce-primary-only", "enforce-desktop"]:
+                        print(_(f"📂 Načten režim ze souboru: {mode}"))
                         return mode
             except: pass
         return "automatic-enabled"
 
-    def _run_check(self, source="Internal"):
-        debug_log(f"Running check logic (Source: {source})")
+    def _save_mode(self, mode):
         try:
-            subprocess.Popen([SCRIPT_PATH])
+            os.makedirs(STATE_DIR, exist_ok=True)
+            with open(STATE_FILE, 'w') as f:
+                f.write(mode)
+            print(_(f"💾 Režim '{mode}' uložen do {STATE_FILE}"))
         except Exception as e:
-            sys.stderr.write(f"Error executing {SCRIPT_PATH}: {e}\n")
+            print(_(f"❌ Chyba configu: {e}"))
 
-    def _set_icon_by_mode(self):
-        names = {
-            "automatic-enabled": ICON_AUTO_NAME,
-            "enforce-primary-only": ICON_PRIMARY_NAME,
-            "enforce-desktop": ICON_DESKTOP_NAME
-        }
-        icon = names.get(self.mode, ICON_AUTO_NAME)
+    # --- D-Bus Metody ---
+    def Trigger(self):
+        if not self.config["enable_dbus"]: return "DISABLED_BY_CONFIG"
+        if self.mode != "automatic-enabled": return f"IGNORED: Mode is {self.mode}"
+        self._run_check("D-Bus")
+        return "OK"
+
+    def SetMode(self, mode_str):
+        if mode_str not in ["automatic-enabled", "enforce-primary-only", "enforce-desktop"]: return "ERROR"
+        print(_(f"📨 D-Bus SetMode: {mode_str}"))
+        self.mode = mode_str
+        self._save_mode(mode_str)
+        self._set_icon_by_mode()
+        self._run_check("D-Bus_SetMode")
+        return _(f"OK: Switched to {mode_str}")
 
-        if self.tray_backend == "sni":
-            self.sni.set_icon(icon)
-        elif self.indicator:
-            full_path = os.path.join(ICON_PATH, f"{icon}.svg")
-            self.indicator.set_icon_full(full_path, icon)
+    def Quit(self):
+        print("🛑 Požadavek na ukončení...")
+        self.quit_callback()
 
     def _launch_settings(self):
-        try:
-            subprocess.Popen([SETTINGS_PATH])
+        try: subprocess.Popen(["/usr/bin/asus-screen-settings.py"])
         except: pass
         return False
 
+    def _run_check(self, source="Internal"):
+        print(_(f"🚀 Spouštím logiku ({source})..."))
+        try: subprocess.Popen([SCRIPT_PATH])
+        except: pass
+
+    def _set_icon_by_mode(self):
+        if self.tray_backend == "sni":
+            if self.mode == "automatic-enabled": self.sni.set_icon(ICON_AUTO_NAME)
+            elif self.mode == "enforce-primary-only": self.sni.set_icon(ICON_PRIMARY_NAME)
+            else: self.sni.set_icon(ICON_DESKTOP_NAME)
+        elif self.indicator:
+            icon_to_set = ICON_NAME
+            if self.mode == "automatic-enabled":
+                if os.path.exists(ICON_AUTO): icon_to_set = ICON_AUTO
+                self.indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE)
+            elif self.mode == "enforce-primary-only":
+                if os.path.exists(ICON_PRIMARY): icon_to_set = ICON_PRIMARY
+                self.indicator.set_status(AppIndicator.IndicatorStatus.ATTENTION)
+            else:
+                if os.path.exists(ICON_DESKTOP): icon_to_set = ICON_DESKTOP
+                self.indicator.set_status(AppIndicator.IndicatorStatus.ATTENTION)
+            try: self.indicator.set_icon(icon_to_set)
+            except: self.indicator.set_icon(ICON_NAME)
+
+    def _on_mode_change(self, widget, mode_name):
+        if widget.get_active():
+            self.mode = mode_name
+            self._save_mode(mode_name)
+            self._set_icon_by_mode()
+            self._run_check("MenuChange")
+
     def _build_menu(self):
         menu = Gtk.Menu()
 
-        title = Gtk.MenuItem(label=_("Asus Screen Control"))
-        title.set_sensitive(False)
-        menu.append(title)
+        item = Gtk.MenuItem(label=_("Asus Screen Control"))
+        item.set_sensitive(False)
+        menu.append(item)
         menu.append(Gtk.SeparatorMenuItem())
 
         r_auto = Gtk.RadioMenuItem(label=_("🤖 Automaticky"))
@@ -262,25 +332,29 @@ class AsusAgent:
         menu.append(r_auto)
 
         group = r_auto.get_group()
-        r_prim = Gtk.RadioMenuItem(label=_("💻 Jen hlavní displej"), group=group)
+        r_prim = Gtk.RadioMenuItem(label=_("💻 Jen hlavní displej"), group=group[0])
         r_prim.connect("toggled", self._on_mode_change, "enforce-primary-only")
         menu.append(r_prim)
 
-        r_both = Gtk.RadioMenuItem(label=_("🖥️🖥️ Oba displeje"), group=group)
+        r_both = Gtk.RadioMenuItem(label=_("🖥️🖥️ Oba displeje"), group=group[0])
         r_both.connect("toggled", self._on_mode_change, "enforce-desktop")
         menu.append(r_both)
 
-        # Nastavení aktivní položky
-        if self.mode == "enforce-primary-only": r_prim.set_active(True)
+        if self.mode == "automatic-enabled": r_auto.set_active(True)
+        elif self.mode == "enforce-primary-only": r_prim.set_active(True)
         elif self.mode == "enforce-desktop": r_both.set_active(True)
-        else: r_auto.set_active(True)
 
         menu.append(Gtk.SeparatorMenuItem())
-
         item_sets = Gtk.MenuItem(label=_("⚙️ Nastavení"))
         item_sets.connect("activate", lambda _: self._launch_settings())
         menu.append(item_sets)
 
+        item_check = Gtk.MenuItem(label=_("Zkontrolovat"))
+        item_check.connect("activate", lambda _: self._run_check())
+        menu.append(item_check)
+
+        menu.append(Gtk.SeparatorMenuItem())
+
         item_quit = Gtk.MenuItem(label=_("Ukončit"))
         item_quit.connect("activate", lambda _: self.Quit())
         menu.append(item_quit)
@@ -288,82 +362,114 @@ class AsusAgent:
         menu.show_all()
         return menu
 
-    def _on_mode_change(self, widget, mode_name):
-        if widget.get_active() and self.mode != mode_name:
-            self.mode = mode_name
-            try:
-                os.makedirs(STATE_DIR, exist_ok=True)
-                with open(STATE_FILE, 'w') as f: f.write(mode_name)
-            except: pass
-            self._set_icon_by_mode()
-            self._run_check("MenuChange")
-
     def _setup_appindicator(self):
         self.indicator = AppIndicator.Indicator.new(
-            "asus-screen-toggler", ICON_AUTO_NAME,
-            AppIndicator.IndicatorCategory.HARDWARE
+            APP_ID, ICON_NAME, AppIndicator.IndicatorCategory.HARDWARE
         )
-        self.indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE)
-        self.indicator.set_icon_theme_path(ICON_PATH)
-        self.indicator.set_menu(self._build_menu())
-        self.tray_backend = "appindicator"
         self._set_icon_by_mode()
+        self.indicator.set_menu(self._build_menu())
 
     def _setup_sni(self):
+        print(_("🔵 Inicializuji KDE StatusNotifierItem (SNI)"))
         self.sni = StatusNotifierItem(self)
-        self.bus.register_object("/StatusNotifierItem", self.sni, None)
-        self.tray_backend = "sni"
-        self._set_icon_by_mode()
+        try:
+            self.bus.register_object("/StatusNotifierItem", self.sni, None)
+            self.tray_backend = "sni"
+            self._set_icon_by_mode()
+            print(_("✅ SNI objekt vytvořen."))
+        except Exception as e:
+            print(_(f"❌ Chyba SNI: {e}"))
+            raise e
+
+    def register_sni_watcher(self):
+        if self.tray_backend == "sni":
+            try:
+                watcher = self.bus.get("org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher")
+                watcher.RegisterStatusNotifierItem(BUS_NAME)
+                print(_("✅ SNI registrováno u KDE Watchera."))
+                self.sni.NewIcon()
+                self.sni.NewStatus()
+            except Exception as e:
+                print(_(f"⚠️ Watcher error: {e}"))
 
+    def _show_gtk_menu(self, button):
         try:
-            watcher = self.bus.get("org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher")
-            watcher.RegisterStatusNotifierItem(BUS_NAME)
-        except: pass
+            self.menu = self._build_menu()
+            self.menu.show_all()
+            self.menu.popup(None, None, None, None, 0, 0)
+        except Exception as e:
+            print(_(f"❌ Chyba při zobrazování menu: {e}"))
+        return False
 
-    def _show_gtk_menu(self):
-        menu = self._build_menu()
-        menu.popup_at_pointer(None)
-
-    # --- D-Bus API ---
-    def SetMode(self, mode):
-        if mode in ["automatic-enabled", "enforce-primary-only", "enforce-desktop"]:
-            self.mode = mode
-            self._on_mode_change(Gtk.MenuItem(), mode) # Simulace aktivace
-            return "OK"
-        return "INVALID_MODE"
 
-    def Quit(self):
-        self.quit_callback()
+def is_kde():
+    return os.environ.get("XDG_CURRENT_DESKTOP", "").lower() == "kde"
 
-def signal_handler(signum, frame):
+# --- Main Boilerplate ---
+loop = None
+publication = None
+
+def quit_app(*args):
+    global publication, loop
+    print(_("\n🧹 Ukončuji..."))
+    if publication:
+        try: publication.unpublish()
+        except: pass
+    if loop: Gtk.main_quit()
+    sys.exit(0)
+
+def signal_handler():
+    # <--- NOVÉ: Kontrola konfigurace pro signály (včetně systémového skriptu)
     if not agent.config["enable_signal"]:
-        return
+        print(_("📩 Signál SIGUSR1 ZAMÍTNUT (vypnuto v configu)."))
+        return True
+
     if agent.mode == "automatic-enabled":
-        agent._run_check("SIGUSR1")
+        print(_("📩 Signál SIGUSR1 přijat!"))
+        agent._run_check("Signal")
+    else:
+        print(_(f"📩 Signál SIGUSR1 ignorován (Režim ze souboru: {agent.mode})."))
+    return True
+
+def sighup_handler():
+    """Obsluha signálu SIGHUP - Reload konfigurace."""
+    print(_("🔄 Signál SIGHUP přijat: Znovunačítám konfiguraci..."))
+    # Zavoláme metodu agenta, která načte soubory znovu
+    agent.config = agent._load_config()
+    return True # Musí vracet True, aby naslouchání pokračovalo
 
 if __name__ == "__main__":
     bus = SessionBus()
 
-    # Singleton kontrola
-    dbus_proxy = bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus")
-    if dbus_proxy.NameHasOwner(BUS_NAME):
+    dbus_sys = bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus")
+    if dbus_sys.NameHasOwner(BUS_NAME):
+        print(_(f"⚠️ Agent už běží."))
         sys.exit(0)
 
-    agent = AsusAgent(quit_callback=lambda: Gtk.main_quit(), bus=bus)
+    agent = AsusAgent(quit_callback=quit_app, bus=bus)
 
     try:
-        bus.publish(BUS_NAME, agent)
+        publication = bus.publish(BUS_NAME, agent)
+        print(_(f"✅ D-Bus jméno {BUS_NAME} získáno."))
+        agent.register_sni_watcher()
     except Exception as e:
-        sys.stderr.write(f"D-Bus publication failed: {e}\n")
+        print(_(f"❌ Start selhal: {e}"))
         sys.exit(1)
 
-    # Signály
-    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1,
-                         lambda: (signal_handler(None, None), True)[1])
-    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP,
-                         lambda: (setattr(agent, 'config', agent._load_config()), True)[1])
-    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, Gtk.main_quit)
-    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, Gtk.main_quit)
+    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1, signal_handler)
+    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, sighup_handler)
+    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, quit_app)
+    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, quit_app)
+
+    print(_(f"✅ Asus Agent GUI spuštěn."))
+    print(_(f"   Režim: {agent.mode}"))
+    print(_(f"   PID: {os.getpid()}"))
 
-    debug_log(f"Asus Agent started (PID: {os.getpid()})")
-    Gtk.main()
+    # Hlavní smyčka v bloku try/finally pro jistotu
+    try:
+        loop = Gtk.main()
+    except KeyboardInterrupt:
+        quit_app()
+    finally:
+        # Záchranná brzda, kdyby Gtk.main() spadlo jinak
+        pass
