#!/usr/bin/env bash
set -euo pipefail

THEME_NAME="${1:-}"

THEME_DIR="$HOME/.config/nucleus-shell/colorschemes"
TARGET="$HOME/.config/nucleus-shell/config/colors.json"

if [[ -z "$THEME_NAME" ]]; then
  echo "Usage: switch-theme.sh <theme-name | auto>"
  exit 1
fi

# === AUTOGENERATED THEME ===
if [[ "$THEME_NAME" == "auto" || "$THEME_NAME" == "autogen" ]]; then
  echo "Generating theme via Quickshell IPC…"

  qs -c nucleus-shell ipc call global regenColors

  echo "Autogenerated theme applied"
  exit 0
fi

# === STATIC THEME ===
SOURCE="$THEME_DIR/$THEME_NAME.json"

if [[ ! -f "$SOURCE" ]]; then
  echo "Theme not found: $THEME_NAME"
  exit 1
fi

# Atomic write
tmp="$(mktemp)"
cat "$SOURCE" > "$tmp"
mv "$tmp" "$TARGET"

echo "Theme switched to: $THEME_NAME"
