"""Profilbild des eigenen Users. UI-frei, kein root.

Schreibt ~/.face (von vielen Greetern/Apps gelesen) und setzt zusätzlich das
AccountsService-Icon (Greeter/Lockscreen) — Letzteres über D-Bus, das für die
EIGENEN Userdaten per polkit ohne Admin erlaubt ist.
"""
from __future__ import annotations

import getpass
import shutil
import subprocess
from pathlib import Path


def _face() -> Path:
    return Path.home() / ".face"


def current_path() -> str | None:
    asv = Path("/var/lib/AccountsService/icons") / getpass.getuser()
    if asv.is_file():
        return str(asv)
    if _face().is_file():
        return str(_face())
    return None


def _user_object_path() -> str | None:
    try:
        r = subprocess.run(
            ["gdbus", "call", "--system", "--dest", "org.freedesktop.Accounts",
             "--object-path", "/org/freedesktop/Accounts",
             "--method", "org.freedesktop.Accounts.FindUserByName", getpass.getuser()],
            capture_output=True, text=True, check=False, timeout=8,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return None
    # Ausgabe: (objectpath '/org/freedesktop/Accounts/User1000',)
    s = r.stdout
    if "'" in s:
        return s.split("'")[1]
    return None


def set_own(image_path: str) -> bool:
    """Profilbild setzen. image_path sollte bereits skaliert sein (PNG)."""
    ok = False
    try:
        shutil.copyfile(image_path, _face())
        ok = True
    except OSError:
        pass
    obj = _user_object_path()
    if obj:
        try:
            subprocess.run(
                ["gdbus", "call", "--system", "--dest", "org.freedesktop.Accounts",
                 "--object-path", obj,
                 "--method", "org.freedesktop.Accounts.User.SetIconFile", image_path],
                check=False, timeout=8,
            )
        except (FileNotFoundError, subprocess.TimeoutExpired):
            pass
    return ok
