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

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Perform a major upgrade of the NixOS configuration."
            echo ""
            echo "This script runs the following steps:"
            echo "  1. Update all flake inputs (nix flake update)"
            echo "  2. Update Doom Emacs to the latest commit"
            echo "  3. Update Claude Code to the latest version"
            echo "  4. Rotate to the next wallpaper"
            echo ""
            echo "After completion, review changes with 'git diff' and rebuild"
            echo "your system with 'sudo nixos-rebuild switch --flake .'"
            echo ""
            echo "Options:"
            echo "  --help, -h    Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

REPO_ROOT="${REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  NixOS Configuration Major Upgrade${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Step 1: Update flake inputs
echo -e "${GREEN}[1/4] Updating flake inputs...${NC}"
cd "$REPO_ROOT"
nix flake update
echo ""

# Step 2: Update Doom Emacs
echo -e "${GREEN}[2/4] Updating Doom Emacs...${NC}"
"$REPO_ROOT/scripts/update-doomemacs.sh"
echo ""

# Step 3: Update Claude Code
echo -e "${GREEN}[3/4] Updating Claude Code...${NC}"
"$REPO_ROOT/packages/claude-code/update.sh"
echo ""

# Step 4: Rotate wallpaper
echo -e "${GREEN}[4/4] Rotating wallpaper...${NC}"
"$REPO_ROOT/scripts/rotate-wallpaper.sh"
echo ""

echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}Upgrade complete!${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo "Next steps:"
echo "  1. Review changes: git diff"
echo "  2. Rebuild system: sudo nixos-rebuild switch --flake ."
echo "  3. If satisfied, commit: git add -A && git commit -m 'chore: Major upgrade'"
