#!/bin/bash
#################################################################
# pacup - Pacman AI Updater
#
# This script analyzes pending Arch Linux updates using a local
# AI model and then asks if you want to proceed with the upgrade.
# It runs as a normal user and only invokes sudo for the final
# pacman command.
#################################################################

# --- Function to run the AI simulation ---
run_simulation() {
    # 1. Check for required command-line tools (pv, ollama).
    local missing_deps=()
    for cmd in pv ollama; do
        if ! command -v "$cmd" &>/dev/null; then
            missing_deps+=("$cmd")
        fi
    done

    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo "Error: This script requires: ${missing_deps[*]}" >&2
        echo "Please install them by running: sudo /usr/bin/pacman -S ${missing_deps[*]}" >&2
        return 1
    fi

    # 2. Get the list of upgradable packages.
    echo "Checking for upgradable packages..."
    local upgrades
    upgrades=$(/usr/bin/pacman -Quq)
    if [ -z "$upgrades" ]; then
        echo "System is already up to date. Nothing to do."
        return 0
    fi
    echo "Found $(echo "$upgrades" | wc -l) packages to upgrade."

    # 3. Ensure the Ollama server is running.
    if ! pgrep -x "ollama" >/dev/null; then
        echo "Starting Ollama server in the background..."
        (ollama serve >/dev/null 2>&1 &)
        sleep 3
    fi

    # 4. Select an AI model based on system resources.
    local model ram_gb cores
    ram_gb=$(free -g | awk '/^Mem:/{print $2}')
    cores=$(nproc)
    if [ "$ram_gb" -ge 32 ] && [ "$cores" -ge 16 ]; then
        model="mistral-nemo"
    elif [ "$ram_gb" -ge 16 ]; then
        model="mistral:7b"
    else
        model="qwen"
    fi
    echo "Selected AI model based on system resources: $model"

    # 5. Build the prompt and send it to the AI for analysis.
    local prompt="In plain language, please provide a brief, one-sentence summary for each of these Arch Linux packages that are about to be updated. Group them by category (e.g., 'System Libraries', 'Kernel', 'Web Browser') if possible:\n\n$upgrades"
    echo -e "\nAnalyzing packages with AI..."
    echo -e "$prompt" | ollama run "$model"
    echo -e "\nAnalysis complete."
    
    return 0 # Indicate success
}

# --- Main Script Logic ---
# All of this runs as the regular user.

echo "--- Pacman AI Update Simulator ---"
run_simulation

# Check the exit code of the simulation function
if [ $? -ne 0 ]; then
    echo "Simulation failed. Aborting."
    exit 1
fi

# After the analysis, prompt the user to proceed with the real update.
echo "----------------------------------------"
read -p "Do you want to proceed with the actual system upgrade now? (y/N) " -n 1 -r proceed_choice
echo

if [[ "$proceed_choice" =~ ^[Yy]$ ]]; then
    echo "Proceeding with update... You will be prompted for your password."
    # This is the ONLY part that runs with elevated privileges.
    sudo /usr/bin/pacman -Syu
else
    echo "Update aborted by user."
    exit 0
fi
