#!/usr/bin/bash
# ABOUTME: Waybar module that outputs HID++ device battery status as JSON.
# ABOUTME: Finds the correct hidpp_battery_* entry dynamically by MODEL_NAME (argument).

if [ -z "$1" ]; then
    echo "Usage: moonarch-waybar-hidpp <model_name>" >&2
    exit 1
fi

MODEL="$1"

for dev in /sys/class/power_supply/hidpp_battery_*; do
    [ -d "$dev" ] || continue
    name=$(cat "$dev/model_name" 2>/dev/null)
    if [ "$name" = "$MODEL" ]; then
        capacity=$(cat "$dev/capacity" 2>/dev/null)
        status=$(cat "$dev/status" 2>/dev/null)

        if [ -z "$capacity" ]; then
            exit 0
        fi

        class="normal"
        if [ "$capacity" -le 20 ]; then
            class="critical"
        elif [ "$capacity" -le 35 ]; then
            class="warning"
        fi

        if [ "$status" = "Charging" ]; then
            text="${capacity}% 󰂄"
        else
            text="${capacity}% 󰌌"
        fi

        tooltip="${name}: ${capacity}% (${status})"

        jq --compact-output -n \
            --arg text "$text" \
            --arg tooltip "$tooltip" \
            --arg class "$class" \
            --argjson percentage "$capacity" \
            '{text: $text, tooltip: $tooltip, class: $class, percentage: $percentage}'
        exit 0
    fi
done

# Device not found — no output, Waybar hides the module
