"""Session-environment resolution and process launching.

A trimmed version of hosts/thin-client's/hosts/touch-panel's sway_control.py: this
device has only one Sway workspace and two possible kiosk destinations — pantry-vision
(the everyday screen) and identity's registration page (on demand) — so there is no
workspace-switching or window-focus surface to wrap, just enough to run the right
launcher script with the graphical session's environment.
"""

from __future__ import annotations

import glob
import logging
import os
import subprocess

log = logging.getLogger(__name__)


def runtime_dir() -> str:
    return os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"


def session_env() -> dict[str, str]:
    env = dict(os.environ)
    env["XDG_RUNTIME_DIR"] = runtime_dir()
    env.setdefault("DBUS_SESSION_BUS_ADDRESS", f"unix:path={runtime_dir()}/bus")
    env.setdefault("WAYLAND_DISPLAY", "wayland-1")
    matches = sorted(glob.glob(os.path.join(runtime_dir(), "sway-ipc.*.sock")))
    if matches:
        env["SWAYSOCK"] = matches[-1]
    return env


def _launch(command: list[str]) -> None:
    log.info("launching %s", " ".join(command))
    try:
        subprocess.Popen(
            command,
            env=session_env(),
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            start_new_session=True,
        )
    except OSError as exc:
        log.error("could not launch %s: %s", command[0], exc)


def launch_pantry_kiosk(fragment: str) -> None:
    _launch(["/usr/local/bin/pantry-kiosk", fragment] if fragment else ["/usr/local/bin/pantry-kiosk"])


def launch_identity_kiosk() -> None:
    _launch(["/usr/local/bin/identity-kiosk"])
