#!/usr/bin/env bash
set -euo pipefail
# POS: entertainment config — Show or edit the entertainment config (ENABLED auto-trigger list, weather location)
# POS_CONFIG: entertainment | entertainment.env | ENABLED=:Auto-trigger list (plugin, interval pairs)::weather,5m joke,10m | *plugins

source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")/common.sh"
source "$(dirname "$0")/../lib/entertainment-lib.sh" 2>/dev/null || source "$(dirname "$0")/entertainment-lib.sh"

keys_section() {
    # Renders the Keys reference: ENABLED + every key declared by installed
    # plugins (via their # POS_KEYS: headers), aligned by key name.
    local d="$1" maxw=8 line key plugin desc req
    while IFS= read -r line; do
        IFS='|' read -r _plugin key _desc _req <<<"$line"
        [ ${#key} -gt "$maxw" ] && maxw=${#key}
    done <<< "$(config_keys "$d")"

    printf '  %-*s %s\n' "$maxw" "ENABLED" "Auto-trigger list: comma-separated 'plugin, interval' pairs,"
    printf '  %-*s %s\n' "$maxw" "" "e.g. ENABLED=\"weather, 5m gold, 1h\""
    while IFS= read -r line; do
        [ -n "$line" ] || continue
        IFS='|' read -r plugin key desc req <<<"$line"
        printf '  %-*s %s (%s)  [%s]\n' "$maxw" "$key" "$desc" "$req" "$plugin"
    done <<< "$(config_keys "$d")"
    printf '  %-*s %s\n' "$maxw" "<any>" "UPPER_SNAKE key settable freely; a warning is shown if no installed plugin declares it"
}

usage() {
    cat <<EOF
Usage: pos entertainment config [get KEY | set KEY=VALUE ... | unset KEY | ls | edit]

Manage the entertainment config file.

Subcommands:
  (none)        Show the whole config file + the declared keys reference
  get KEY       Print the current value of one key ('(not set)' if absent)
  set KEY=V...  Set one or more keys (validated first, all-or-nothing)
  unset KEY     Remove a key from the file
  ls            Declared keys with their current values, aligned
  edit          Interactive editor for the entertainment scope
After 'set'/'unset'/'edit', auto-trigger timers are re-synced from ENABLED.

Config file: $CONFIG_FILE

Keys (declared by the installed plugins' # POS_KEYS: headers):
$(keys_section "$(ent_plugin_dir)")

Intervals: 5m 10m 15m 30m 45m hourly 2h 6h 12h daily weekly, or OnCalendar=...

Examples:
  pos entertainment config
  pos entertainment config ls
  pos entertainment config get WEATHER_LAT
  pos entertainment config set WEATHER_LAT=36.51 WEATHER_LON=40.75
  pos entertainment config set ENABLED=""
  pos entertainment config unset WEATHER_CITY
  pos entertainment config edit
EOF
    exit 0
}

key_known() {
    config_key_known "$(ent_plugin_dir)" "$1"
}

case "${1:-}" in
    -h|--help) usage ;;
    get)
        shift
        [ $# -eq 1 ] || usage
        v="$(config_value "$1")"
        [ -n "$v" ] && printf '%s\n' "$v" || echo "(not set)"
        ;;
    unset)
        shift
        [ $# -eq 1 ] || usage
        write_config_key "$1" "-"
        ok "$1 removed from $CONFIG_FILE"
        sync_timers
        ;;
    ls)
        shift
        maxw=8
        while IFS= read -r line; do
            IFS='|' read -r _plugin key _desc _req <<<"$line"
            [ ${#key} -gt "$maxw" ] && maxw=${#key}
        done <<< "$(config_keys "$(ent_plugin_dir)")"
        printf '  %-*s %s\n' "$maxw" "ENABLED" "\"$(config_value ENABLED)\""
        while IFS= read -r line; do
            [ -n "$line" ] || continue
            IFS='|' read -r plugin key desc req <<<"$line"
            v="$(config_value "$key")"
            printf '  %-*s %s  [%s] %s (%s)\n' "$maxw" "$key" "${v:-<not set>}" "$plugin" "$desc" "$req"
        done <<< "$(config_keys "$(ent_plugin_dir)")"
        ;;
    edit)
        shift
        source "$(dirname "$0")/../lib/config-ui.sh" 2>/dev/null || source "$(dirname "$0")/config-ui.sh"
        cfg_ui entertainment
        ;;
    set)
        shift
        [ $# -ge 1 ] || usage
        # Validate every KEY=VALUE pair first — all or nothing, so a typo'd
        # arg (e.g. 'ENABLED ="x"') can't partially write or clear a key.
        for pair in "$@"; do
            case "$pair" in
                *=*)
                    key="${pair%%=*}"
                    val="${pair#*=}"
                    ;;
                *)
                    err "Invalid entry '$pair' — expected KEY=VALUE with no spaces around '=', e.g. ENABLED=\"gold, 1h\""
                    ;;
            esac
            [[ "$key" =~ ^[A-Z][A-Z0-9_]*$ ]] || \
                err "Invalid key '$key' in '$pair' (expected UPPER_SNAKE, e.g. WEATHER_LAT)"
            [ -z "$val" ] && [ "$key" != "ENABLED" ] && err "No value given for '$key' (expected $key=...)"
            key_known "$key" || warn "Key '$key' not referenced by any installed plugin — saving anyway"
        done
        for pair in "$@"; do
            key="${pair%%=*}"
            val="${pair#*=}"
            write_config_key "$key" "$val"
            ok "$key saved to $CONFIG_FILE"
        done
        sync_timers
        ;;
    *)
        echo "Config: $CONFIG_FILE"
        if [ -f "$CONFIG_FILE" ]; then
            cat "$CONFIG_FILE"
        else
            echo "(not created yet — run 'pos entertainment enable <plugin> [interval]' or 'pos entertainment config set ...')"
        fi
        echo
        echo "ENABLED: $(config_value ENABLED)"
        echo "Intervals: 5m 10m 15m 30m 45m hourly 2h 6h 12h daily weekly, or OnCalendar=..."
        echo
        echo "Plugin keys (declared in each plugin's # POS_KEYS: header):"
        keys_section "$(ent_plugin_dir)"
        ;;
esac
