#!/usr/bin/env bash
# Mirror TANINUX's accent into eww.
#   get     print the accent hex (from gui.json, fallback default)
#   apply   write it into eww.scss's $accent-dim line + eww reload (if changed)
#   watch   apply now, then re-apply whenever gui.json changes
#
# Contract: ~/.local/share/taninux/gui.json -> field accent_hex (#rrggbb).
# Only the $accent-dim line is managed; $accent + washes derive from it in SCSS.
set -u

SCSS="$HOME/.config/eww/eww.scss"
GUI="${XDG_DATA_HOME:-$HOME/.local/share}/taninux/gui.json"
DEFAULT="#8f8aac"   # ume — same as the spec's fallback

get() {
  local h=""
  [ -f "$GUI" ] && h=$(jq -r '.accent_hex // empty' "$GUI" 2>/dev/null)
  case "$h" in
    \#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]) printf '%s' "$h" ;;
    *) printf '%s' "$DEFAULT" ;;
  esac
}

current() {
  grep -m1 -oE '^\$accent-dim:[[:space:]]*#[0-9a-fA-F]{6}' "$SCSS" 2>/dev/null | grep -oE '#[0-9a-fA-F]{6}'
}

apply() {
  local hex; hex=$(get)
  [ "$(current)" = "$hex" ] && return 0          # nothing changed
  # awk handles the literal `$` in `$accent-dim` cleanly (no sed escaping pain)
  awk -v hex="$hex" '
    /accent_hex \(managed/ { print "$accent-dim: " hex ";   // accent_hex (managed by scripts/accent.sh)"; next }
    { print }
  ' "$SCSS" > "$SCSS.tmp" && mv "$SCSS.tmp" "$SCSS"
  eww reload 2>/dev/null
}

case "${1:-apply}" in
  get)   get; echo ;;
  apply) apply ;;
  watch)
    apply
    last=$(stat -c %Y "$GUI" 2>/dev/null || echo 0)
    while :; do
      sleep 2
      now=$(stat -c %Y "$GUI" 2>/dev/null || echo 0)
      if [ "$now" != "$last" ]; then last="$now"; apply; fi
    done
    ;;
esac
