#!/usr/bin/env python3
import os
import re
import subprocess
import sys

cfg_file = os.path.expanduser("~/.config/plasma-org.kde.plasma.desktop-appletsrc")
containments = []
current_plugin = "org.kde.image"

if os.path.exists(cfg_file):
    try:
        with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
            content = f.read()

        # Find containments that declare a wallpaper plugin
        matches = re.findall(r'\[Containments\]\[(\d+)\][^\[]*?wallpaperplugin=([^\r\n]+)', content)
        if matches:
            containments = [m[0] for m in matches]
            current_plugin = matches[0][1].strip()
        else:
            # Fallback to any containments specifying activityId
            acts = re.findall(r'\[Containments\]\[(\d+)\][^\[]*?activityId=', content)
            containments = acts if acts else ["37"]
    except Exception:
        containments = ["37"]
else:
    containments = ["37"]

# Cycle order:
# 1. org.kde.image (Static Artwork) -> 2. org.alfred.aquarium (Live Cyber Aquarium) -> 3. org.alfred.burningbush (Sovereign Fire) -> 1.
if current_plugin == "org.alfred.aquarium":
    next_plugin = "org.alfred.burningbush"
    desc = "Sovereign Fire (Rising GPU Embers)"
elif current_plugin == "org.alfred.burningbush":
    next_plugin = "org.kde.image"
    desc = "Static Artwork (Gold Edition)"
else:
    next_plugin = "org.alfred.aquarium"
    desc = "Live Cyber Aquarium (Swimming Penguins)"

# Set the wallpaperplugin on all desktop containments
for cid in set(containments):
    subprocess.run([
        "kwriteconfig6",
        "--file", "plasma-org.kde.plasma.desktop-appletsrc",
        "--group", "Containments",
        "--group", str(cid),
        "--key", "wallpaperplugin", next_plugin
    ], check=False)

import shutil

# Notify the user on desktop if notify-send is available
if shutil.which("notify-send"):
    try:
        subprocess.run([
            "notify-send",
            "-i", "preferences-desktop-wallpaper",
            "Alfred Wallpaper",
            f"Switched to {desc}"
        ], check=False)
    except Exception:
        pass

# Restart plasmashell smoothly under systemd
try:
    subprocess.run(["systemctl", "--user", "restart", "plasma-plasmashell.service"], check=False)
except Exception:
    subprocess.run(["kquitapp6", "plasmashell"], check=False)
    subprocess.run(["kstart", "plasmashell"], check=False)
