#!/usr/bin/env zsh

# Color definitions
autoload -U colors && colors
BOLD="\033[1m"
RESET="\033[0m"
GREEN="\033[32m"
BLUE="\033[34m"
YELLOW="\033[33m"
RED="\033[31m"

# Configuration
SCRIPT_DIR="${0:a:h}"
SYSTEM_DIR="${SCRIPT_DIR}/../system"
MODULES_DIR="${SCRIPT_DIR}/.."
CONFIG_TARGET="/etc/nixos/configuration.nix"
MODULES_TARGET="/etc/nixos/modules"

# Function to print colored messages (use printf for portability)
print_info()  { printf "%b\n" "${BLUE}${BOLD}[INFO]${RESET} $1"; }
print_success(){ printf "%b\n" "${GREEN}${BOLD}[SUCCESS]${RESET} $1"; }
print_error() { printf "%b\n" "${RED}${BOLD}[ERROR]${RESET} $1"; }
print_warn()  { printf "%b\n" "${YELLOW}${BOLD}[WARN]${RESET} $1"; }

# Check if running from correct directory
if [[ ! -d "$SYSTEM_DIR" ]]; then
    print_error "System directory not found: $SYSTEM_DIR"
    exit 1
fi

# Get available system configurations (use portable glob + basename)
systems=()
for f in "$SYSTEM_DIR"/*.nix; do
    [ -f "$f" ] || continue
    base="$(basename "$f")"
    systems+=("${base%.nix}")
done

if [[ ${#systems[@]} -eq 0 ]]; then
    print_error "No system configurations found in $SYSTEM_DIR"
    exit 1
fi

# Check for command-line argument
selected_system=""
if [[ -n "$1" ]]; then
    # Argument provided, check membership with an explicit loop
    for s in "${systems[@]}"; do
        if [[ "$s" == "$1" ]]; then
            selected_system="$1"
            break
        fi
    done

    if [[ -n "$selected_system" ]]; then
        print_info "Preselected system: ${BOLD}${selected_system}${RESET}"
    else
        print_error "Invalid system: $1"
        print_info "Available systems: ${systems[*]}"
        exit 1
    fi
else
    # Interactive selection
    print_info "Available system configurations:"
    echo ""

    i=1
    for s in "${systems[@]}"; do
        printf "  %b)%b %s\n" "${GREEN}${i}" "${RESET}" "$s"
        i=$((i+1))
    done
    echo ""

    # Prompt for selection
    while true; do
        printf "%b" "${BOLD}Select a system configuration (1-${#systems[@]}): ${RESET}"
        read -r selection

        if [[ "$selection" =~ ^[0-9]+$ ]] && (( selection >= 1 && selection <= ${#systems[@]} )); then
            selected_system="${systems[$selection]}"
            break
        else
            print_error "Invalid selection. Please enter a number between 1 and ${#systems[@]}"
        fi
    done
fi

# Confirm selection
print_info "Selected: ${BOLD}${selected_system}${RESET}"
printf "%b" "${YELLOW}${BOLD}Continue? (y/N): ${RESET}"
read -r confirm

if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    print_warn "Aborted by user"
    exit 0
fi

# Execute deployment steps
print_info "Starting deployment..."
echo ""

# Step 1: Git pull
print_info "Pulling latest changes from git..."
if git pull; then
    print_success "Git pull completed"
else
    print_error "Git pull failed"
    exit 1
fi

# Step 2: Sync modules directory
print_info "Syncing modules to ${BOLD}${MODULES_TARGET}${RESET}..."
if sudo rsync -av --delete --exclude='scripts' "${MODULES_DIR}/" "${MODULES_TARGET}/"; then
    print_success "Modules synced"
else
    print_error "Failed to sync modules"
    exit 1
fi

## Todo System Conditional pulling of directories (only if it exists)

# Step 2.1: Sync secrets directory
# nix-system-configs/modules/scripts  /pull.zsh
# nix-system-configs/secrets/songsheet/secrets.yaml
SECRETS_DIR="${SCRIPT_DIR}/../../secrets"
SECRETS_TARGET="/etc/nixos/secrets"

if [[ -d "$SECRETS_DIR" ]]; then
    print_info "Syncing secrets to ${BOLD}${SECRETS_TARGET}${RESET}..."
    if sudo rsync -av --delete "${SECRETS_DIR}/" "${SECRETS_TARGET}/"; then
        print_success "Secrets synced"
    else
        print_error "Failed to sync secrets"
        exit 1
    fi
else
    print_warn "Secrets directory not found: ${SECRETS_DIR}"
fi

# Step 2.2: Sync styling directory (copy custom themes, templates, css etc.)
STYLING_DIR="${SCRIPT_DIR}/../styling"
STYLING_TARGET="/etc/styling"

if [[ -d "$STYLING_DIR" ]]; then
    print_info "Syncing styling to ${BOLD}${STYLING_TARGET}${RESET}..."
    if sudo rsync -av --delete "${STYLING_DIR}/" "${STYLING_TARGET}/"; then
        print_success "Styling synced"
    else
        print_error "Failed to sync styling"
        exit 1
    fi
else
    print_warn "Styling directory not found: ${STYLING_DIR}"
fi

# Step 2.3: Sync system_scripts directory
SYSTEM_SCRIPT_DIR="${SCRIPT_DIR}/../system_scripts"
SYSTEM_SCRIPT_TARGET="/etc/nixos/system_scripts"

if [[ -d "$SYSTEM_SCRIPT_DIR" ]]; then
    print_info "Syncing system scripts to ${BOLD}${SYSTEM_SCRIPT_TARGET}${RESET}..."
    if sudo rsync -av --delete "${SYSTEM_SCRIPT_DIR}/" "${SYSTEM_SCRIPT_TARGET}/"; then
        print_success "System scripts synced"
    else
        print_error "Failed to sync system scripts"
        exit 1
    fi
else
    print_warn "System scripts directory not found: ${SYSTEM_SCRIPT_DIR}"
fi


# Step 3: Copy configuration
source_file="${SYSTEM_DIR}/${selected_system}.nix"
print_info "Copying ${BOLD}${source_file}${RESET} to ${BOLD}${CONFIG_TARGET}${RESET}..."

if sudo cp "$source_file" "$CONFIG_TARGET"; then
    print_success "Configuration copied"
else
    print_error "Failed to copy configuration"
    exit 1
fi

# Step 4: Rebuild system
print_info "Rebuilding NixOS system..."
echo ""
if sudo nixos-rebuild switch --upgrade-all; then
    print_success "System rebuild completed successfully!"
else
    print_error "System rebuild failed"
    exit 1
fi

echo ""
print_success "${BOLD}Deployment complete!${RESET}"
print_info "System: ${BOLD}${selected_system}${RESET}"
