#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# bea's KDE rice — CachyOS / Plasma 6 setup script
# Applies: colors, style, icons, cursors, window rules, and installs widgets
# ─────────────────────────────────────────────────────────────────────────────

set -euo pipefail

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
info()    { echo -e "${GREEN}[+]${NC} $*"; }
warn()    { echo -e "${YELLOW}[!]${NC} $*"; }
die()     { echo -e "${RED}[✗]${NC} $*"; exit 1; }

require() { command -v "$1" &>/dev/null || die "Required command not found: $1"; }

require plasma-apply-colorscheme
require plasma-apply-desktoptheme
require plasma-apply-cursortheme
require kwriteconfig6
require lookandfeeltool
require plasmapkg2

# ─── 1. COLOR SCHEME — KDE Material You Dark ────────────────────────────────
info "Applying color scheme: MaterialYouDark"
COLORSCHEME="MaterialYouDark"
COLORSCHEME_URL="https://store.kde.org/p/1620895"

if plasma-apply-colorscheme --list-schemes 2>/dev/null | grep -q "$COLORSCHEME"; then
    plasma-apply-colorscheme "$COLORSCHEME"
else
    warn "Color scheme '$COLORSCHEME' not installed."
    warn "Install it from: $COLORSCHEME_URL"
    warn "Or: Settings → Appearance → Colors → Get New Colors"
fi

# ─── 2. APPLICATION STYLE — Darkly ──────────────────────────────────────────
info "Setting application style: Darkly"
DARKLY_URL="https://github.com/Bali10050/Darkly"

if kpackagetool6 --list --type=KWin/Decoration 2>/dev/null | grep -qi darkly || \
   [ -f "$HOME/.local/share/plasma/desktoptheme/Darkly/metadata.json" ]; then
    kwriteconfig6 --file kdeglobals --group KDE --key widgetStyle "Darkly"
    dbus-send --session --dest=org.kde.KWin /KWin org.kde.KWin.reloadConfig 2>/dev/null || true
else
    warn "Darkly style not installed. Build and install from: $DARKLY_URL"
fi

# ─── 3. PLASMA STYLE — CachyOS Nord ─────────────────────────────────────────
info "Applying Plasma style: CachyOS-Nord"
PLASMA_THEME="CachyOS-Nord"

if plasma-apply-desktoptheme --list-themes 2>/dev/null | grep -q "$PLASMA_THEME"; then
    plasma-apply-desktoptheme "$PLASMA_THEME"
else
    warn "Plasma theme '$PLASMA_THEME' not found."
    warn "Install from: Settings → Appearance → Plasma Style → Get New Plasma Styles"
    warn "Search for 'CachyOS Nord'"
fi

# ─── 4. WINDOW DECORATIONS — Breeze ─────────────────────────────────────────
info "Setting window decorations: Breeze"
kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key library "org.kde.breeze"
kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key theme "__aurorae__svg__Breeze"

# ─── 5. ICONS — char-white ───────────────────────────────────────────────────
info "Setting icon theme: char-white"
ICON_THEME="char-white"
ICON_URL="https://store.kde.org/p/1340791"

if [ -d "$HOME/.local/share/icons/$ICON_THEME" ] || \
   [ -d "/usr/share/icons/$ICON_THEME" ]; then
    kwriteconfig6 --file kdeglobals --group Icons --key Theme "$ICON_THEME"
else
    warn "Icon theme '$ICON_THEME' not installed."
    warn "Install from: $ICON_URL"
    warn "Or: Settings → Appearance → Icons → Get New Icons → search 'char-white'"
fi

# ─── 6. CURSORS — Breeze Dark ────────────────────────────────────────────────
info "Applying cursor theme: Breeze_Dark"
if plasma-apply-cursortheme --list-themes 2>/dev/null | grep -q "Breeze_Dark"; then
    plasma-apply-cursortheme Breeze_Dark
else
    # Breeze_Dark ships with plasma-workspace, set manually if tool unavailable
    kwriteconfig6 --file kcminputrc --group Mouse --key cursorTheme "Breeze_Dark"
    warn "plasma-apply-cursortheme failed; wrote to kcminputrc directly."
fi

# ─── 7. WINDOW RULE — 95% opacity ────────────────────────────────────────────
info "Adding window rule: 95% opacity for all windows"
RULES_FILE="$HOME/.config/kwinrulesrc"
RULE_GROUP="1"

# Check if rule already exists
if grep -q "opacityactive=95" "$RULES_FILE" 2>/dev/null; then
    warn "Opacity rule already exists in kwinrulesrc, skipping."
else
    # Count existing rules to append correctly
    EXISTING=$(grep -c "^\[" "$RULES_FILE" 2>/dev/null || echo 0)
    RULE_GROUP=$((EXISTING + 1))

    cat >> "$RULES_FILE" <<EOF

[$RULE_GROUP]
Description=95% opacity - all windows
opacityactive=95
opacityactiverule=2
opacityinactive=90
opacityinactiverule=2
wmclass=.*
wmclassmatch=3
EOF

    # Update the count in [General]
    if grep -q "^\[General\]" "$RULES_FILE" 2>/dev/null; then
        COUNT=$(grep "^count=" "$RULES_FILE" 2>/dev/null | cut -d= -f2 || echo 0)
        NEW_COUNT=$((COUNT + 1))
        sed -i "s/^count=.*/count=$NEW_COUNT/" "$RULES_FILE"
    else
        echo -e "[General]\ncount=1" >> "$RULES_FILE"
    fi
fi

# ─── 8. PANEL WIDGETS — install via plasmapkg2 ───────────────────────────────
info "Installing panel widgets..."

declare -A WIDGETS=(
    ["Panel Colorizer"]="https://store.kde.org/p/2130967"
    ["Modern Clock"]="https://store.kde.org/p/2136283"
    ["Network Speed"]="https://store.kde.org/p/2136283"
    ["Kurve (CPU/RAM)"]="https://store.kde.org/p/2136283"
    ["PlasMusic Toolbar"]="https://store.kde.org/p/1920214"
    ["Peek (Window Peek)"]="https://store.kde.org/p/2136283"
    ["Bismuth/Parachute Bin"]="https://store.kde.org/p/2136283"
)

warn "The following widgets must be installed manually from the KDE Store"
warn "or via Settings → Widgets → Get New Widgets:"
echo ""
for WIDGET in "${!WIDGETS[@]}"; do
    echo -e "  ${GREEN}•${NC} $WIDGET  →  ${WIDGETS[$WIDGET]}"
done
echo ""
warn "After installing, add them to your panel left-to-right:"
echo "  Application Launcher → Modern Clock → Network Speed → Core Usage"
echo "  → Kurve → Icons Only Task Manager → PlasMusic Toolbar"
echo "  → System Tray → Peek → Bin"

# ─── 9. FONTS (match plasma defaults) ────────────────────────────────────────
info "Setting fonts to Plasma defaults..."
kwriteconfig6 --file kdeglobals --group General --key font "Noto Sans,10,-1,5,50,0,0,0,0,0"
kwriteconfig6 --file kdeglobals --group General --key fixed "Hack,10,-1,5,50,0,0,0,0,0"
kwriteconfig6 --file kdeglobals --group General --key toolBarFont "Noto Sans,10,-1,5,50,0,0,0,0,0"
kwriteconfig6 --file kdeglobals --group General --key menuFont "Noto Sans,10,-1,5,50,0,0,0,0,0"
kwriteconfig6 --file kdeglobals --group WM --key activeFont "Noto Sans,10,-1,5,50,0,0,0,0,0"

# ─── 10. RELOAD KDE ──────────────────────────────────────────────────────────
info "Reloading KDE settings..."
dbus-send --session --dest=org.kde.KWin /KWin org.kde.KWin.reloadConfig 2>/dev/null || true
qdbus6 org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.refreshCurrentShell 2>/dev/null || \
    qdbus org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.refreshCurrentShell 2>/dev/null || \
    warn "Could not auto-refresh Plasma shell — you may need to log out and back in."

# ─── DONE ─────────────────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN} Rice applied! A log-out/log-in may be needed for all     ${NC}"
echo -e "${GREEN} changes (especially style + decorations) to take effect. ${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
