#!/bin/bash
wall_dir="${1:?wallpaper directory required}"
interval="${2:-1800}"

pick_wall() {
    find "$wall_dir" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | shuf -n1
}

set_wall() { [ -n "$1" ] && xwallpaper --zoom "$1"; }

has_fullscreen() {
    python3 - <<'EOF'
import json, subprocess, sys

def is_fullscreen(node):
    if node.get('window') and node.get('fullscreen_mode', 0) > 0: return True
    return any(is_fullscreen(c) for c in node.get('nodes', []) + node.get('floating_nodes', []))

def find_ws(node, name):
    if node.get('type') == 'workspace' and node.get('name') == name: return node
    for c in node.get('nodes', []) + node.get('floating_nodes', []):
        r = find_ws(c, name)
        if r: return r

try:
    wss = json.loads(subprocess.check_output(['i3-msg', '-t', 'get_workspaces'], stderr=subprocess.DEVNULL))
    tree = json.loads(subprocess.check_output(['i3-msg', '-t', 'get_tree'], stderr=subprocess.DEVNULL))
    for ws in wss:
        if ws.get('visible'):
            node = find_ws(tree, ws['name'])
            if node and is_fullscreen(node):
                sys.exit(0)
except Exception:
    pass
sys.exit(1)
EOF
}

# Initial wallpaper
set_wall "$(pick_wall)"

while sleep "$interval"; do
    has_fullscreen || set_wall "$(pick_wall)"
done
