# ABOUTME: Entry point for Moongreet — sets up GTK Application and Layer Shell.
# ABOUTME: Handles CLI invocation and initializes the greeter window.

import sys
from importlib.resources import files

import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Gdk", "4.0")
from gi.repository import Gtk, Gdk

from moongreet.greeter import GreeterWindow

# gtk4-layer-shell is optional for development/testing
try:
    gi.require_version("Gtk4LayerShell", "1.0")
    from gi.repository import Gtk4LayerShell
    HAS_LAYER_SHELL = True
except (ValueError, ImportError):
    HAS_LAYER_SHELL = False


class MoongreetApp(Gtk.Application):
    """GTK Application for the Moongreet greeter."""

    def __init__(self) -> None:
        super().__init__(application_id="dev.moonarch.moongreet")

    def do_activate(self) -> None:
        """Create and present the greeter window."""
        self._register_icons()
        self._load_css()
        window = GreeterWindow(application=self)

        if HAS_LAYER_SHELL:
            self._setup_layer_shell(window)

        window.present()

    def _register_icons(self) -> None:
        """Register custom icons from the package data/icons directory."""
        icons_dir = files("moongreet") / "data" / "icons"
        icon_theme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default())
        icon_theme.add_search_path(str(icons_dir))

    def _load_css(self) -> None:
        """Load the CSS stylesheet for the greeter."""
        css_provider = Gtk.CssProvider()
        css_path = files("moongreet") / "style.css"
        css_provider.load_from_path(str(css_path))
        Gtk.StyleContext.add_provider_for_display(
            Gdk.Display.get_default(),
            css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
        )

    def _setup_layer_shell(self, window: Gtk.Window) -> None:
        """Configure gtk4-layer-shell for fullscreen greeter display."""
        Gtk4LayerShell.init_for_window(window)
        Gtk4LayerShell.set_layer(window, Gtk4LayerShell.Layer.TOP)
        Gtk4LayerShell.set_keyboard_mode(
            window, Gtk4LayerShell.KeyboardMode.EXCLUSIVE
        )
        # Anchor to all edges for fullscreen
        for edge in [
            Gtk4LayerShell.Edge.TOP,
            Gtk4LayerShell.Edge.BOTTOM,
            Gtk4LayerShell.Edge.LEFT,
            Gtk4LayerShell.Edge.RIGHT,
        ]:
            Gtk4LayerShell.set_anchor(window, edge, True)


def main() -> None:
    """Run the Moongreet application."""
    app = MoongreetApp()
    app.run(sys.argv)


if __name__ == "__main__":
    main()
