#!/usr/bin/python3

import os
from pathlib import Path
import re
import subprocess
import sys


CHANNEL = "xfce4-desktop"


def xfconf(channel, property_name, *options):
    command = ["xfconf-query", "--channel", channel]
    if property_name is not None:
        command.extend(["--property", property_name])
    result = subprocess.run(
        command + list(options), capture_output=True, text=True, timeout=10
    )
    return result.stdout.rstrip("\n") if result.returncode == 0 else None


def monitor_prefixes(randr, workspace_count):
    screen = 0
    for line in randr.splitlines():
        header = re.match(r"Screen (\d+):", line)
        if header:
            screen = int(header[1])
        monitor = re.match(
            r"(\S+) connected (?:primary )?\d+x\d+[+-]\d+[+-]\d+(?:\s|$)", line
        )
        if monitor:
            for workspace in range(workspace_count):
                yield f"/backdrop/screen{screen}/monitor{monitor[1]}/workspace{workspace}"


def initialize(wallpaper, randr, workspace_count, properties):
    for prefix in monitor_prefixes(randr, workspace_count):
        if any(name.startswith(prefix + "/") for name in properties):
            continue
        for name, kind, value in [
            ("color-style", "int", "0"),
            ("image-style", "int", "5"),
            ("last-image", "string", wallpaper),
        ]:
            property_name = prefix + "/" + name
            result = xfconf(
                CHANNEL, property_name, "--create", "--type", kind, "--set", value
            )
            if result is None:
                raise RuntimeError(f"Unable to initialize {property_name}")
            properties.add(property_name)


def main():
    desktops = os.environ.get("XDG_CURRENT_DESKTOP", "").upper().split(":")
    if "XFCE" not in desktops or not os.environ.get("DISPLAY"):
        return 0
    if os.environ.get("XDG_SESSION_TYPE") == "wayland":
        return 0

    # Only the new Parrot skel opts in; existing profiles are left unchanged.
    wallpaper = xfconf(CHANNEL, "/backdrop/echo-default-wallpaper")
    if not wallpaper or not Path(wallpaper).is_file():
        return 0

    properties = xfconf(CHANNEL, None, "--list")
    if properties is None:
        raise RuntimeError("Unable to read the existing desktop configuration")
    count = xfconf("xfwm4", "/general/workspace_count")
    try:
        workspace_count = max(1, int(count))
    except (TypeError, ValueError):
        workspace_count = 1
    randr = subprocess.run(
        ["xrandr", "--query"], capture_output=True, text=True, check=True,
        timeout=10, env={**os.environ, "LC_ALL": "C"},
    )
    initialize(wallpaper, randr.stdout, workspace_count, set(properties.splitlines()))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, subprocess.SubprocessError, RuntimeError) as error:
        print(f"Echo wallpaper defaults: {error}", file=sys.stderr)
        sys.exit(1)
