This is pretty much what this solution does, but through udev.
Systemd, D-Bus, and udev can be used separately or together to make this easier to listen in userland, it will just be dependent on your distribution or setup.
The kernel essentially flags the power source through udev, and the rule triggers the script. That can be done programmatically instead of a script as well. libudev is there for that: https://www.freedesktop.org/software/systemd/man/latest/libu...
https://wiki.archlinux.org/title/Udev (userland /dev is what udev does)