#!/bin/bash

# Quick Fix for Paperless AI Database Issues
# This script provides immediate steps to resolve the database mismatch

set -e

echo "🚨 Quick Fix for Paperless AI Database Issues"
echo "============================================="

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

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

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

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

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    print_error "Docker is not running. Please start Docker first."
    exit 1
fi

echo ""
print_status "Step 1: Stopping current Paperless AI container..."

# Stop and remove current Paperless AI container
if docker ps | grep -q "paperless-ai"; then
    PAPERLESS_AI_CONTAINER=$(docker ps --filter "name=paperless-ai" --format "{{.Names}}" | head -1)
    if [[ -n "$PAPERLESS_AI_CONTAINER" ]]; then
        print_warning "Stopping container: $PAPERLESS_AI_CONTAINER"
        docker stop "$PAPERLESS_AI_CONTAINER"
        docker rm "$PAPERLESS_AI_CONTAINER"
        print_success "Container stopped and removed"
    fi
else
    print_status "No running Paperless AI container found"
fi

echo ""
print_status "Step 2: Checking Paperless-ngx status..."

# Check if Paperless-ngx is running
if docker ps | grep -q "paperless"; then
    PAPERLESS_CONTAINER=$(docker ps --filter "name=paperless" --format "{{.Names}}" | head -1)
    print_success "Paperless-ngx is running: $PAPERLESS_CONTAINER"
    
    # Show current database configuration
    echo ""
    print_status "Current Paperless-ngx database configuration:"
    docker exec "$PAPERLESS_CONTAINER" env | grep -E "(PAPERLESS_DB|PAPERLESS_REDIS)" | sort
else
    print_error "Paperless-ngx is not running. Please start it first."
    exit 1
fi

echo ""
print_status "Step 3: Creating backup of current Paperless AI data..."

# Backup current Paperless AI data
if docker volume ls | grep -q "paperless-ai"; then
    BACKUP_DIR="backups/paperless-ai-$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    
    print_status "Creating backup in: $BACKUP_DIR"
    
    # Create a temporary container to copy data
    docker run --rm -v paperless-ai_paperless-ai_data:/data -v "$(pwd)/$BACKUP_DIR:/backup" alpine tar czf /backup/paperless-ai-data-backup.tar.gz -C /data .
    
    if [[ -f "$BACKUP_DIR/paperless-ai-data-backup.tar.gz" ]]; then
        print_success "Backup created successfully"
    else
        print_warning "Backup creation failed"
    fi
else
    print_status "No existing Paperless AI data volume found"
fi

echo ""
print_status "Step 4: Setting up proper integration..."

# Create the environment file if it doesn't exist
ENV_FILE="stacks/ai/.env"
if [[ ! -f "$ENV_FILE" ]]; then
    print_status "Creating environment file template..."
    mkdir -p "$(dirname "$ENV_FILE")"
    
    cat > "$ENV_FILE" << 'EOF'
# Paperless AI Environment Configuration
# Generated on $(date)

# Paperless-ngx Connection Settings
PAPERLESS_URL=https://paperless.pressmess.duckdns.org
PAPERLESS_USERNAME=admin
PAPERLESS_PASSWORD=your_password_here

# API Token (optional - will be generated if not provided)
PAPERLESS_API_TOKEN=

# AI Provider Configuration (configure at least one)
OPENAI_API_KEY=
OLLAMA_BASE_URL=http://ollama:11434
DEEPSEEK_API_KEY=
AZURE_OPENAI_API_KEY=
AZURE_OPENAI_ENDPOINT=

# Processing Configuration
PAPERLESS_AI_AUTO_TAG=true
PAPERLESS_AI_AUTO_TITLE=true
PAPERLESS_AI_CONFIDENCE_THRESHOLD=0.7
PAPERLESS_AI_PROCESSING_INTERVAL=300
EOF
    
    print_success "Environment file template created: $ENV_FILE"
    print_warning "Please edit this file with your actual credentials and API keys"
else
    print_status "Environment file already exists: $ENV_FILE"
fi

echo ""
print_status "Step 5: Instructions for proper setup..."

echo "🔧 To properly fix the database issue, follow these steps:"
echo ""
echo "1. Edit the environment file:"
echo "   nano $ENV_FILE"
echo ""
echo "2. Configure your credentials and API keys:"
echo "   - Set PAPERLESS_PASSWORD to your actual admin password"
echo "   - Configure at least one AI provider (OpenAI, Ollama, etc.)"
echo ""
echo "3. Deploy the new configuration:"
echo "   cd stacks/ai"
echo "   docker-compose -f paperless-ai.yml --env-file .env up -d"
echo ""
echo "4. Verify the integration:"
echo "   ./scripts/verify_paperless_ai.sh"
echo ""

print_warning "IMPORTANT: The new configuration will:"
echo "   - Connect to the same database as Paperless-ngx"
echo "   - Use the same Redis instance"
echo "   - Share the same network"
echo "   - Access the same document storage"
echo ""

print_success "Quick fix completed!"
echo ""
echo "📋 Next steps:"
echo "1. Configure your environment file"
echo "2. Deploy the new Paperless AI configuration"
echo "3. Test the integration"
echo ""
echo "🔍 For detailed diagnostics, run:"
echo "   ./scripts/diagnose_paperless_issues.sh"
