#!/usr/bin/python3
"""VolnOS dock guard — keep the Software Center pinned to the dock.

Runs once per login from /etc/xdg/autostart. The Software Center is pinned by
default via the dconf 'favorite-apps' default (00-volnos-defaults), but defaults
are user-overridable: if the user un-pins it, this re-adds it on the next login.
Run once per session (not a live monitor) so it is never a tug-of-war.

Gated on the gnome-initial-setup completion stamp so it only acts once first-run
setup is finished — i.e. the pin appears "after the welcome/OOBE", as intended.

Deliberately self-contained (no import of volnos_software): the desktop id is
duplicated here on purpose. Keep it identical to DESKTOP_ID in
volnos_software/__init__.py and to the favorite-apps entry in 00-volnos-defaults.
"""
import os
import sys

DESKTOP_ID = "com.volnos.SoftwareCenter.desktop"
_SCHEMA = "org.gnome.shell"
_KEY = "favorite-apps"


def _oobe_done() -> bool:
    """True once gnome-initial-setup has completed for this user."""
    base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
        os.path.expanduser("~"), ".config")
    return os.path.exists(os.path.join(base, "gnome-initial-setup-done"))


def ensure_pinned() -> bool:
    """Append DESKTOP_ID to favorite-apps if missing. Returns True if it changed."""
    from gi.repository import Gio

    source = Gio.SettingsSchemaSource.get_default()
    if source is None or source.lookup(_SCHEMA, True) is None:
        return False  # not a GNOME Shell session — nothing to pin
    settings = Gio.Settings.new(_SCHEMA)
    favorites = list(settings.get_strv(_KEY))
    if DESKTOP_ID in favorites:
        return False
    favorites.append(DESKTOP_ID)
    settings.set_strv(_KEY, favorites)
    Gio.Settings.sync()  # flush the write before the short-lived process exits
    return True


def main() -> int:
    if not _oobe_done():
        return 0  # first-run setup still in progress; act on a later login
    try:
        ensure_pinned()
    except Exception:  # noqa: BLE001 — a guard must never break login
        return 0
    return 0


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