"""Shared window / dock branding for IuVe Connect Agent Console."""

from __future__ import annotations

from pathlib import Path
from typing import Any, Callable

CONSOLE_WM_CLASS = "iuve-connect-agent"
CONSOLE_ICON_NAME = "iuve-connect-agent"


def resolve_brand_icon_path() -> Path | None:
    """Resolve installed or packaged IuVe brand icon for GTK windows."""
    ui_dir = Path(__file__).resolve().parent
    candidates = (
        Path("/opt/iuve-connect-desktop-agent/share/icons/iuve-connect-agent.svg"),
        Path("/usr/share/icons/hicolor/scalable/apps/iuve-connect-agent.svg"),
        Path(
            "/opt/iuve-connect-desktop-agent/iuve_connect_agents/desktop/packaging/linux/icons/iuve-connect-agent.svg"
        ),
        ui_dir.parent / "packaging" / "linux" / "icons" / "iuve-connect-agent.svg",
        ui_dir.parent.parent.parent / "app" / "static" / "icons" / "iuve_favicon.svg",
        ui_dir.parent.parent.parent / "app" / "static" / "favicon.svg",
        ui_dir.parent.parent.parent / "app" / "static" / "icons" / "iuve_logo_symbol.svg",
    )
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    return None


def apply_application_icon(app: Any, gtk_module: Any | None = None) -> None:
    """Set Gtk.Application icon so the dock/taskbar uses IuVe branding."""
    try:
        app.set_icon_name(CONSOLE_ICON_NAME)
        return
    except Exception:
        pass
    icon_path = resolve_brand_icon_path()
    if icon_path is None:
        return
    try:
        if gtk_module is not None and hasattr(gtk_module, "Texture"):
            texture = gtk_module.Texture.new_from_filename(str(icon_path))
            if texture is not None and hasattr(app, "set_icon"):
                app.set_icon(texture)
                return
    except Exception:
        pass
    try:
        from gi.repository import Gdk  # type: ignore

        texture = Gdk.Texture.new_from_filename(str(icon_path))
        if texture is not None and hasattr(app, "set_icon"):
            app.set_icon(texture)
    except Exception:
        pass


def apply_window_icon(window: Any, *, icon_path: Path | None = None) -> None:
    """Apply themed or file-based icon to a Gtk.Window."""
    try:
        window.set_icon_name(CONSOLE_ICON_NAME)
        return
    except Exception:
        pass
    resolved = icon_path or resolve_brand_icon_path()
    if resolved is None:
        return
    try:
        from gi.repository import Gdk  # type: ignore

        texture = Gdk.Texture.new_from_filename(str(resolved))
        if texture is not None and hasattr(window, "set_icon"):
            window.set_icon(texture)
    except Exception:
        pass


def apply_window_wm_class(window: Any) -> None:
    """Set WM_CLASS so KDE/GNOME dock groups under StartupWMClass."""

    def _on_realize(_widget: Any) -> None:
        try:
            surface = window.get_surface()
        except Exception:
            return
        if surface is None:
            return
        try:
            surface.set_class(CONSOLE_WM_CLASS, "IuVe Connect Agent")
        except Exception:
            pass

    try:
        window.connect("realize", _on_realize)
    except Exception:
        pass


def center_window_on_primary_monitor(
    window: Any,
    *,
    width: int,
    height: int,
    glib_idle_add: Callable[..., Any] | None = None,
) -> None:
    """Center a Gtk.Window on the primary monitor after realize."""

    def _center_once() -> bool:
        try:
            from gi.repository import Gdk  # type: ignore

            display = window.get_display()
            monitor = display.get_primary_monitor() if display is not None else None
            if monitor is None:
                return False
            geometry = monitor.get_geometry()
            surface = window.get_surface()
            if surface is None:
                return False
            layout = Gdk.ToplevelLayout.new()
            x = geometry.x + max(0, (geometry.width - width) // 2)
            y = geometry.y + max(0, (geometry.height - height) // 2)
            surface.set_geometry(layout, x, y, width, height)
        except Exception:
            pass
        return False

    def _schedule_center(_widget: Any) -> None:
        if glib_idle_add is not None:
            glib_idle_add(_center_once)
        else:
            _center_once()

    try:
        window.connect("realize", _schedule_center)
    except Exception:
        if glib_idle_add is not None:
            glib_idle_add(_center_once)
        else:
            _center_once()
