#!/usr/bin/env bash

# Set the system theme declaratively.
# Usage: nomarchy-theme-set <theme-name>

THEME_NAME="$1"

if [[ -z $THEME_NAME ]]; then
  echo "Usage: nomarchy-theme-set <theme-name>"
  exit 1
fi

STATE_DIR="$HOME/.config/home-manager"
THEME_STATE_FILE="$STATE_DIR/theme-state.nix"
WALLPAPER_STATE_FILE="$STATE_DIR/wallpaper-state.nix"

# Logic for finding themes
if [ -d "/etc/nixos/nomarchy/themes" ]; then
  THEMES_DIR="/etc/nixos/nomarchy/themes"
elif [ -d "/etc/nomarchy/themes" ]; then
  THEMES_DIR="/etc/nomarchy/themes"
else
  THEMES_DIR="/etc/nixos/themes"
fi

mkdir -p "$STATE_DIR"

if [ ! -d "$THEMES_DIR/$THEME_NAME" ] && ! [[ "$THEME_NAME" == "dracula" || "$THEME_NAME" == "nord" ]]; then
  echo "Theme '$THEME_NAME' not found in $THEMES_DIR"
  # Check if it exists in the palettes file
  # (Assuming nomarchy-palettes.nix is imported in Nix)
fi

echo "$THEME_NAME" > "$THEME_STATE_FILE"

# Try to find a background for this theme
BG_DIR="$THEMES_DIR/$THEME_NAME/backgrounds"
if [ -d "$BG_DIR" ]; then
  BG=$(ls "$BG_DIR" | head -n 1)
  if [ -n "$BG" ]; then
    echo "$BG_DIR/$BG" > "$WALLPAPER_STATE_FILE"
  fi
fi

echo "Theme set to $THEME_NAME. Applying changes with env-update..."
env-update

nomarchy-hook theme-set "$THEME_NAME"
