#!/bin/bash

# GoodMem Uninstall Script
#
# This script completely removes GoodMem from your system including containers,
# images, CLI tools, and configuration files.
#
# Usage:
#   ~/.goodmem/uninstall.sh [OPTIONS]
#
# Options:
#   -f, --force         Skip confirmation prompts
#   -h, --help          Show this help message
#
# Examples:
#   ~/.goodmem/uninstall.sh                       # Interactive uninstall (asks for confirmation)
#   ~/.goodmem/uninstall.sh --force               # Force uninstall without prompts
#
# What this script does:
#   1. Detects if using local or remote database configuration
#   2. Stops and removes all GoodMem containers (server + local database if applicable)
#   3. Removes GoodMem Docker images (asks about PostgreSQL image removal)
#   4. Finds and removes the CLI binary from system PATH
#   5. Completely removes the ~/.goodmem configuration directory
#
# IMPORTANT - Data Warning:
#   - This will PERMANENTLY DELETE all your memories, spaces, and data
#   - Local database containers and volumes will be completely removed
#   - For remote databases: you must manually delete the database instance
#   - Make sure to backup any important data before proceeding
#
# Prerequisites:
#   - Docker and Docker Compose must be available
#   - User must have permissions to run docker commands

set -euo pipefail

# Configuration
readonly GOODMEM_DIR="$HOME/.goodmem"
readonly DOCKER_COMPOSE_FILE="$GOODMEM_DIR/docker-compose.yml"
readonly DB_CONTAINER_NAME="goodmem-db"
readonly SERVER_CONTAINER_NAME="goodmem-server"

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

# Parse command line arguments
FORCE_MODE=false

show_help() {
    echo "GoodMem Uninstall Script"
    echo
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  -f, --force         Skip confirmation prompts"
    echo "  -h, --help          Show this help message"
    echo
    echo "This script will:"
    echo "  1. Detect if using local or remote database"
    echo "  2. Stop and remove all GoodMem containers and volumes"
    echo "  3. Remove GoodMem Docker images (ask about PostgreSQL image)"
    echo "  4. Find and remove the CLI binary from system PATH"
    echo "  5. Completely remove the ~/.goodmem directory"
    echo
    echo "WARNING: This will permanently delete ALL GoodMem data and configuration"
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -f|--force)
                FORCE_MODE=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo -e "${RED}Error: Unknown option '$1'${NC}" >&2
                echo "Use --help for usage information." >&2
                exit 1
                ;;
        esac
    done
}

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

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Check if required tools are available
check_prerequisites() {
    log_info "Checking prerequisites..."

    # Check if docker is available
    if ! command -v docker &> /dev/null; then
        log_error "Docker is not installed or not in PATH"
        exit 1
    fi

    # Check if user can run docker commands
    if ! docker ps &> /dev/null; then
        log_error "Cannot run docker commands"
        log_error "Please ensure your user is in the docker group or run with sudo"
        exit 1
    fi

    log_success "All prerequisites met"
}

# Detect database configuration type
detect_database_type() {
    local env_file="$GOODMEM_DIR/.env"
    local config_file="$GOODMEM_DIR/config.json"

    # Method 1: Check .env file for DB_URL pattern
    if [[ -f "$env_file" ]]; then
        if grep -q "DB_URL=jdbc:postgresql://db:" "$env_file" 2>/dev/null; then
            echo "local"
            return 0
        elif grep -q "DB_URL=jdbc:postgresql://" "$env_file" 2>/dev/null; then
            echo "remote"
            return 0
        fi
    fi

    # Method 2: Check config.json file
    if [[ -f "$config_file" ]]; then
        if grep -q '"database.*localhost\|"database.*db:' "$config_file" 2>/dev/null; then
            echo "local"
            return 0
        elif grep -q '"database.*host"' "$config_file" 2>/dev/null; then
            echo "remote"
            return 0
        fi
    fi

    # Method 3: Check if database container exists
    if docker ps -a --format "{{.Names}}" | grep -q "^${DB_CONTAINER_NAME}$"; then
        echo "local"
        return 0
    fi

    # Method 4: Check docker-compose for database service
    if [[ -f "$DOCKER_COMPOSE_FILE" ]]; then
        if grep -q "services:.*db:" "$DOCKER_COMPOSE_FILE" 2>/dev/null || \
           grep -q "container_name:.*goodmem-db" "$DOCKER_COMPOSE_FILE" 2>/dev/null; then
            echo "local"
            return 0
        fi
    fi

    # Default to unknown if cannot determine
    echo "unknown"
}

# Show remote database warning
show_remote_database_warning() {
    echo
    log_warning "🗄️  Remote Database Detected"
    echo
    log_info "This installation uses a remote PostgreSQL database."
    log_info "The uninstall script will only remove local GoodMem components."
    echo
    log_warning "⚠️  You must MANUALLY delete your remote database to completely remove all data:"
    echo
    log_info "For NeonDB:"
    log_info "  1. Go to https://console.neon.tech"
    log_info "  2. Navigate to your project dashboard"
    log_info "  3. Delete the database or entire project"
    echo
    log_info "For other providers:"
    log_info "  1. Log into your cloud provider console (AWS RDS, GCP Cloud SQL, etc.)"
    log_info "  2. Delete the PostgreSQL instance used by GoodMem"
    echo
    log_warning "The remote database will NOT be touched by this uninstall script."
    echo
}

# Confirm action with user
confirm_uninstall() {
    if [[ "$FORCE_MODE" == true ]]; then
        return 0
    fi

    local db_type
    db_type=$(detect_database_type)

    if [[ "$db_type" == "remote" ]]; then
        show_remote_database_warning
    fi

    echo
    echo -e "${RED}⚠️  WARNING: This will completely remove GoodMem from your system ⚠️${NC}"
    echo
    echo "This will:"
    echo "  1. Stop and remove all GoodMem containers"
    if [[ "$db_type" == "local" ]]; then
        echo "  2. Remove local PostgreSQL database with ALL DATA"
    elif [[ "$db_type" == "remote" ]]; then
        echo "  2. Skip database removal (using remote database)"
    else
        echo "  2. Remove any local database containers found"
    fi
    echo "  3. Remove GoodMem Docker images (ask about PostgreSQL image)"
    echo "  4. Remove CLI binary from system PATH"
    echo "  5. DELETE ~/.goodmem folder with ALL configuration"
    echo
    echo -e "${RED}🚨 THIS WILL PERMANENTLY DELETE ALL YOUR MEMORIES AND DATA! 🚨${NC}"
    if [[ "$db_type" == "remote" ]]; then
        echo -e "${YELLOW}📡 Remember to manually delete your remote database afterwards!${NC}"
    fi
    echo

    read -p "Are you absolutely sure you want to continue? [y/N]: " -r
    echo

    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Uninstall cancelled by user"
        exit 0
    fi
}

# Stop and remove containers
stop_and_remove_containers() {
    log_info "Step 1: Stopping and removing GoodMem containers..."

    # Change to goodmem directory if it exists
    if [[ -d "$GOODMEM_DIR" && -f "$DOCKER_COMPOSE_FILE" ]]; then
        cd "$GOODMEM_DIR"

        # Stop all services first
        log_info "Stopping all GoodMem services..."
        if docker compose ps --quiet | grep -q .; then
            docker compose down --volumes
            log_success "All services stopped and removed"
        else
            log_info "No running services found"
        fi
    else
        log_info "No docker-compose.yml found, checking for individual containers..."

        # Remove containers individually
        for container in "$SERVER_CONTAINER_NAME" "$DB_CONTAINER_NAME"; do
            if docker ps -a --format "{{.Names}}" | grep -q "^${container}$"; then
                log_info "Removing container: $container"
                docker stop "$container" >/dev/null 2>&1 || true
                docker rm "$container" >/dev/null 2>&1 || true
                log_success "Container $container removed"
            else
                log_info "Container $container not found, skipping"
            fi
        done
    fi

    # Remove any remaining goodmem-related containers
    local remaining_containers
    remaining_containers=$(docker ps -a --format "{{.Names}}" | grep "goodmem" || true)
    if [[ -n "$remaining_containers" ]]; then
        log_info "Found additional GoodMem containers, removing..."
        echo "$remaining_containers" | while read -r container; do
            if [[ -n "$container" ]]; then
                docker stop "$container" >/dev/null 2>&1 || true
                docker rm "$container" >/dev/null 2>&1 || true
                log_info "Removed: $container"
            fi
        done
    fi

    log_success "All containers removed"
}

# Remove Docker images
remove_images() {
    log_info "Step 2: Removing Docker images..."

    # Remove all goodmem-related images (server, embedders, etc.)
    local goodmem_images
    goodmem_images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "goodmem" || true)

    if [[ -n "$goodmem_images" ]]; then
        log_info "Removing all GoodMem images..."
        echo "$goodmem_images" | while read -r image; do
            if [[ -n "$image" ]]; then
                docker rmi "$image" >/dev/null 2>&1 || true
                log_info "Removed: $image"
            fi
        done
        log_success "All GoodMem images removed"
    else
        log_info "No GoodMem images found"
    fi

    # Ask about PostgreSQL images (only concern user with)
    local postgres_images
    postgres_images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep -E "postgres|pgvector" || true)

    if [[ -n "$postgres_images" ]]; then
        if [[ "$FORCE_MODE" != true ]]; then
            echo
            log_warning "Found PostgreSQL/pgvector images that may be used by other applications:"
            echo "$postgres_images" | while read -r image; do
                echo "  $image"
            done
            echo
            log_info "These images might be used by other Docker applications on your system."
            read -p "Do you want to remove PostgreSQL images as well? [y/N]: " -r
            echo
        else
            REPLY="n"  # Default to keeping PostgreSQL images in force mode
        fi

        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Removing PostgreSQL images..."
            echo "$postgres_images" | while read -r image; do
                if [[ -n "$image" ]]; then
                    docker rmi "$image" >/dev/null 2>&1 || true
                    log_info "Removed: $image"
                fi
            done
            log_success "PostgreSQL images removed"
        else
            log_info "PostgreSQL images preserved (may be used by other applications)"
        fi
    else
        log_info "No PostgreSQL images found"
    fi
}

# Remove CLI binary
remove_cli() {
    log_info "Step 3: Removing CLI binary..."

    # Try to find goodmem CLI using which command
    local cli_path
    cli_path=$(which goodmem 2>/dev/null || echo "")

    if [[ -n "$cli_path" ]]; then
        log_info "Found CLI at: $cli_path"

        # Check if we have permission to remove it
        local cli_dir
        cli_dir=$(dirname "$cli_path")

        if [[ -w "$cli_dir" ]]; then
            rm -f "$cli_path"
            log_success "CLI binary removed from: $cli_path"
        else
            log_warning "Cannot remove CLI binary (insufficient permissions)"
            log_info "Please manually remove: $cli_path"
            log_info "You may need to run: sudo rm $cli_path"
        fi
    else
        log_info "CLI binary not found in PATH, checking common locations..."

        # Check common installation locations
        local common_paths=(
            "/usr/local/bin/goodmem"
            "/usr/bin/goodmem"
            "$HOME/.local/bin/goodmem"
            "$HOME/bin/goodmem"
        )

        local found=false
        for path in "${common_paths[@]}"; do
            if [[ -f "$path" ]]; then
                log_info "Found CLI at: $path"
                if [[ -w "$(dirname "$path")" ]]; then
                    rm -f "$path"
                    log_success "CLI binary removed from: $path"
                else
                    log_warning "Cannot remove CLI binary (insufficient permissions)"
                    log_info "Please manually remove: $path"
                fi
                found=true
                break
            fi
        done

        if [[ "$found" != true ]]; then
            log_info "CLI binary not found in common locations"
        fi
    fi
}

# Remove configuration directory
remove_config_directory() {
    log_info "Step 4: Removing configuration directory..."

    if [[ -d "$GOODMEM_DIR" ]]; then
        log_info "Removing: $GOODMEM_DIR"

        # Show what will be deleted
        if [[ "$FORCE_MODE" != true ]]; then
            echo
            echo "Contents to be deleted:"
            ls -la "$GOODMEM_DIR" 2>/dev/null | head -10 || echo "  (Cannot list contents)"

            # Calculate directory size
            local dir_size
            dir_size=$(du -sh "$GOODMEM_DIR" 2>/dev/null | cut -f1 || echo "unknown")
            log_info "Directory size: $dir_size"
            echo

            read -p "This will permanently delete all configuration and data. Continue? [y/N]: " -r
            echo

            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                log_warning "Keeping ~/.goodmem folder - GoodMem not fully uninstalled"
                log_info "To complete uninstall later, manually run: rm -rf ~/.goodmem"
                return 1
            fi
        fi

        rm -rf "$GOODMEM_DIR"
        log_success "Configuration directory completely removed"
    else
        log_info "Configuration directory not found, skipping"
    fi
}

# Clean up Docker networks
cleanup_docker_networks() {
    log_info "Cleaning up Docker networks..."

    # Find goodmem-related networks
    local goodmem_networks
    goodmem_networks=$(docker network ls --format "{{.Name}}" | grep "goodmem" || true)

    if [[ -n "$goodmem_networks" ]]; then
        echo "$goodmem_networks" | while read -r network; do
            if [[ -n "$network" ]]; then
                # Only remove if no containers are using it
                local network_containers
                network_containers=$(docker network inspect "$network" --format '{{len .Containers}}' 2>/dev/null || echo "0")

                if [[ "$network_containers" == "0" ]]; then
                    docker network rm "$network" >/dev/null 2>&1 || true
                    log_info "Removed network: $network"
                else
                    log_info "Network $network still in use, skipping"
                fi
            fi
        done
    else
        log_info "No GoodMem networks found"
    fi
}

# Show final status
show_uninstall_summary() {
    echo
    log_success "=== GoodMem Uninstall Complete ==="
    echo

    # Check what's left
    local remaining_containers remaining_images cli_still_exists config_still_exists

    remaining_containers=$(docker ps -a --format "{{.Names}}" | grep "goodmem" || true)
    remaining_images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "goodmem" || true)
    cli_still_exists=$(which goodmem 2>/dev/null || echo "")
    config_still_exists="$([[ -d "$GOODMEM_DIR" ]] && echo "yes" || echo "no")"

    # Check if fully uninstalled
    local db_type
    db_type=$(detect_database_type 2>/dev/null || echo "unknown")

    if [[ -z "$remaining_containers" && -z "$remaining_images" && -z "$cli_still_exists" && "$config_still_exists" == "no" ]]; then
        log_success "✅ GoodMem has been completely removed from your system"

        if [[ "$db_type" == "remote" ]]; then
            echo
            log_warning "📡 Don't forget to manually delete your remote database:"
            log_info "  - NeonDB: https://console.neon.tech"
            log_info "  - AWS RDS: https://console.aws.amazon.com/rds"
            log_info "  - GCP Cloud SQL: https://console.cloud.google.com/sql"
        fi
    else
        log_info "Uninstall status:"

        if [[ -n "$remaining_containers" ]]; then
            log_warning "⚠️  Some containers remain:"
            echo "$remaining_containers" | while read -r container; do
                echo "    $container"
            done
        fi

        if [[ -n "$remaining_images" ]]; then
            log_warning "⚠️  Some images remain:"
            echo "$remaining_images" | while read -r image; do
                echo "    $image"
            done
        fi

        if [[ -n "$cli_still_exists" ]]; then
            log_warning "⚠️  CLI binary still exists: $cli_still_exists"
        fi

        if [[ "$config_still_exists" == "yes" ]]; then
            log_warning "⚠️  Configuration directory still exists: $GOODMEM_DIR"
            log_info "To complete removal: rm -rf $GOODMEM_DIR"
        fi
    fi

    echo
    log_info "To reinstall GoodMem, run:"
    log_info "  curl -s https://get.goodmem.ai | bash"
}

# Main execution
main() {
    parse_args "$@"

    echo "=== GoodMem Uninstall Script ==="
    echo

    check_prerequisites
    confirm_uninstall

    echo
    log_info "Starting GoodMem uninstall process..."
    echo

    stop_and_remove_containers
    echo

    remove_images
    echo

    remove_cli
    echo

    cleanup_docker_networks
    echo

    remove_config_directory

    show_uninstall_summary
}

# Run main function if script is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi