#!/usr/bin/env bash
#
# GDELT CLI Uninstaller
#
# Removes the gdelt CLI tool from the system.
#
# Usage:
#   ./uninstall.sh
#

set -euo pipefail

BINARY_NAME="gdelt"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

success() {
    echo -e "${GREEN}[OK]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

# Find and remove binary
remove_binary() {
    local locations=(
        "${HOME}/.local/bin/${BINARY_NAME}"
        "/usr/local/bin/${BINARY_NAME}"
        "${HOME}/.cargo/bin/${BINARY_NAME}"
    )

    local found=false

    for loc in "${locations[@]}"; do
        if [[ -f "$loc" ]]; then
            info "Found binary at: $loc"
            read -p "Remove $loc? [y/N] " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                rm -f "$loc"
                success "Removed $loc"
                found=true
            fi
        fi
    done

    if [[ "$found" != "true" ]]; then
        warn "No gdelt binary found in standard locations"
    fi
}

# Remove data directories
remove_data() {
    local data_dirs=(
        "${HOME}/.local/share/gdelt"
        "${HOME}/.cache/gdelt"
        "${HOME}/.config/gdelt"
    )

    for dir in "${data_dirs[@]}"; do
        if [[ -d "$dir" ]]; then
            info "Found data directory: $dir"
            read -p "Remove $dir and all its contents? [y/N] " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                rm -rf "$dir"
                success "Removed $dir"
            fi
        fi
    done
}

main() {
    echo ""
    echo "=========================================="
    echo "       GDELT CLI Uninstaller"
    echo "=========================================="
    echo ""

    remove_binary
    echo ""

    read -p "Also remove data directories (cache, config, database)? [y/N] " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        remove_data
    fi

    echo ""
    success "Uninstall complete"
}

main "$@"
