local THRESHOLD_MINUTES = 7200 -- Default threshold for dead devices in minutes
local NOTIFICATION_ICON = 1059 -- Notification icon ID

-- Whitelist of device names to exclude from notifications
local WHITELISTED_DEVICES = {
    "Mode 1",
    "System Status",
    "Living Room Sensor",
}

return {
    active = true,
    
    on = {
        timer = { 'every 1 hours' }
    },

    logging = {
        level = domoticz.LOG_INFO,
        marker = "DEVICE_MONITOR"
    },

    execute = function(domoticz)
        local powerDevice = domoticz.devices("Power Monitor")
        if not powerDevice or powerDevice.state ~= "On" then
            return
        end

        -- Check if a device is in the whitelist
        local function isWhitelisted(deviceName)
            for _, name in ipairs(WHITELISTED_DEVICES) do
                if deviceName == name then
                    return true
                end
            end
            return false
        end

        -- Filter devices that haven't updated within the threshold and are not whitelisted
        local deadDevices = domoticz.devices().filter(function(device)
            return device.lastUpdate 
                and device.lastUpdate.minutesAgo > THRESHOLD_MINUTES 
                and not isWhitelisted(device.name)
        end)

        -- Process each dead device
        deadDevices.forEach(function(deadDevice)
            local notificationText = "Inactive device detected: "
            notificationText = notificationText .. 
                deadDevice.name .. " (Last update: " .. 
                deadDevice.lastUpdate.minutesAgo .. " mins ago)"
            
            -- Log message
            domoticz.log(notificationText, domoticz.LOG_INFO)

            -- Format the JSON payload for notifications
            local payload = {
                text = notificationText,
                icon = NOTIFICATION_ICON
            }
            local payloadJSON = domoticz.utils.toJSON(payload)
            
            domoticz.log("Sending notification: " .. payloadJSON, domoticz.LOG_INFO)

            -- Send the JSON to the Notification Sender device
            local notificationDevice = domoticz.devices('Notification Sender')
            if notificationDevice then
                notificationDevice.setDescription(payloadJSON)
                notificationDevice.switchOn().afterSec(2)
            else
                domoticz.log("Notification Sender device not found", domoticz.LOG_ERROR)
            end
        end)
    end
}