#!/usr/bin/env python3
"""Windows XP System Event Sound Daemon (USB insert/remove & battery warnings)."""

import fcntl
import os
import subprocess
import sys
import threading
import time
from pathlib import Path

LOCK_PATH = f"/run/user/{os.getuid()}/xp-sound-daemon.lock"
SOUND_SCRIPT = "/home/carsten/.config/hypr/scripts/xp-sound.sh"


def play(name):
    subprocess.Popen([SOUND_SCRIPT, name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def usb_monitor():
    last_event = {"add": 0.0, "remove": 0.0}
    while True:
        try:
            proc = subprocess.Popen(
                ["udevadm", "monitor", "--udev", "--subsystem-match=usb"],
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                text=True,
                bufsize=1,
            )
            for line in proc.stdout:
                if "(usb)" not in line:
                    continue
                # Filter to top-level USB devices (avoid firing multiple times for sub-interfaces like 1-2:1.0)
                if ":" in line.rsplit("/", 1)[-1]:
                    continue
                now = time.monotonic()
                if " add " in line and now - last_event["add"] > 1.0:
                    last_event["add"] = now
                    play("hardware-insert")
                elif " remove " in line and now - last_event["remove"] > 1.0:
                    last_event["remove"] = now
                    play("hardware-removed")
            proc.wait()
        except Exception:
            time.sleep(5)


def battery_monitor():
    warned_low = False
    warned_crit = False
    while True:
        try:
            bats = list(Path("/sys/class/power_supply").glob("BAT*"))
            if bats:
                bat = bats[0]
                status = (bat / "status").read_text().strip().lower()
                cap = int((bat / "capacity").read_text().strip())
                if status == "discharging":
                    if cap <= 7 and not warned_crit:
                        warned_crit = True
                        warned_low = True
                        play("battery-critical")
                    elif cap <= 15 and not warned_low:
                        warned_low = True
                        play("battery-low")
                else:
                    warned_low = False
                    warned_crit = False
        except Exception:
            pass
        time.sleep(30)


def main():
    lock_fd = open(LOCK_PATH, "w")
    try:
        fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit(0)

    t_usb = threading.Thread(target=usb_monitor, daemon=True)
    t_bat = threading.Thread(target=battery_monitor, daemon=True)
    t_usb.start()
    t_bat.start()
    t_usb.join()


if __name__ == "__main__":
    main()
