#!/bin/bash
#
# LabAdmin Docker Setup Script
# Interactive setup for LabAdmin Docker deployment
# Can be used standalone or within the source repository
#

set -e

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

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/.env"
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"

# Docker image to use (GitHub Container Registry)
DOCKER_IMAGE="ghcr.io/labadmin-software/labadmin:latest"

# Detect if running in source repository or standalone
if [ -f "$SCRIPT_DIR/backend/app/main.py" ] && [ -f "$SCRIPT_DIR/frontend/package.json" ]; then
    DEPLOYMENT_MODE="development"
else
    DEPLOYMENT_MODE="production"
fi

# Print colored message
print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_header() {
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check and install Docker
check_docker() {
    print_header "Docker Installation Check"
    
    if command_exists docker; then
        DOCKER_VERSION=$(docker --version | cut -d' ' -f3 | cut -d',' -f1)
        print_success "Docker is already installed (version $DOCKER_VERSION)"
        return 0
    fi
    
    print_warning "Docker is not installed"
    read -p "Do you want to install Docker? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_error "Docker is required. Exiting."
        exit 1
    fi
    
    print_info "Installing Docker..."
    
    # Detect OS
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Linux
        if command_exists apt-get; then
            # Debian/Ubuntu
            wget -q https://get.docker.com -O get-docker.sh
            sudo sh get-docker.sh
            sudo usermod -aG docker $USER
            rm get-docker.sh
        elif command_exists yum; then
            # CentOS/RHEL
            sudo yum install -y yum-utils
            sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
            sudo yum install -y docker-ce docker-ce-cli containerd.io
            sudo systemctl start docker
            sudo systemctl enable docker
            sudo usermod -aG docker $USER
        else
            print_error "Unsupported Linux distribution"
            exit 1
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        print_warning "Please install Docker Desktop from https://www.docker.com/products/docker-desktop"
        exit 1
    else
        print_error "Unsupported operating system"
        exit 1
    fi
    
    print_success "Docker installed successfully"
    
    # Apply the group change immediately
    print_info "Applying docker group changes..."
    newgrp docker
    
    print_success "Docker group changes applied"
}

# Check and install Docker Compose
check_docker_compose() {
    print_header "Docker Compose Installation Check"
    
    if docker compose version >/dev/null 2>&1; then
        COMPOSE_VERSION=$(docker compose version --short)
        print_success "Docker Compose is already installed (version $COMPOSE_VERSION)"
        return 0
    fi
    
    print_warning "Docker Compose is not installed"
    read -p "Do you want to install Docker Compose? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_error "Docker Compose is required. Exiting."
        exit 1
    fi
    
    print_info "Installing Docker Compose..."
    
    # Install Docker Compose V2 (plugin)
    DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}
    mkdir -p $DOCKER_CONFIG/cli-plugins
    wget https://github.com/docker/compose/releases/download/v2.24.5/docker-compose-linux-x86_64 -O $DOCKER_CONFIG/cli-plugins/docker-compose
    chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose
    
    print_success "Docker Compose installed successfully"
}

# Generate random secret key
generate_secret_key() {
    if command_exists openssl; then
        openssl rand -hex 32
    else
        # Fallback to /dev/urandom
        head -c 32 /dev/urandom | xxd -p -c 64
    fi
}

# Configure PostgreSQL
configure_postgres() {
    print_header "PostgreSQL Configuration"
    
    echo "How do you want to run PostgreSQL?"
    echo "1) Self-hosted in Docker (recommended for testing/development)"
    echo "2) External PostgreSQL server (recommended for production)"
    read -p "Enter your choice (1-2): " POSTGRES_CHOICE
    
    case $POSTGRES_CHOICE in
        1)
            USE_DOCKER_POSTGRES=true
            print_info "Using self-hosted PostgreSQL in Docker"
            
            read -p "PostgreSQL database name [labadmin]: " POSTGRES_DB
            POSTGRES_DB=${POSTGRES_DB:-labadmin}
            
            read -p "PostgreSQL user [labadmin]: " POSTGRES_USER
            POSTGRES_USER=${POSTGRES_USER:-labadmin}
            
            read -sp "PostgreSQL password [randomly generated]: " POSTGRES_PASSWORD
            echo
            if [ -z "$POSTGRES_PASSWORD" ]; then
                POSTGRES_PASSWORD=$(generate_secret_key | cut -c1-16)
                print_info "Generated password: $POSTGRES_PASSWORD"
            fi
            
            read -p "PostgreSQL port [5432]: " POSTGRES_PORT
            POSTGRES_PORT=${POSTGRES_PORT:-5432}
            
            DATABASE_URL="postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}"
            
            # Ask about backup
            read -p "Enable automatic PostgreSQL backups? (y/n) [y]: " ENABLE_BACKUP
            ENABLE_BACKUP=${ENABLE_BACKUP:-y}
            ;;
        2)
            USE_DOCKER_POSTGRES=false
            print_info "Using external PostgreSQL server"
            
            read -p "PostgreSQL host: " POSTGRES_HOST
            read -p "PostgreSQL port [5432]: " POSTGRES_PORT
            POSTGRES_PORT=${POSTGRES_PORT:-5432}
            
            read -p "PostgreSQL database name: " POSTGRES_DB
            read -p "PostgreSQL user: " POSTGRES_USER
            read -sp "PostgreSQL password: " POSTGRES_PASSWORD
            echo
            
            DATABASE_URL="postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
            
            ENABLE_BACKUP=n
            ;;
        *)
            print_error "Invalid choice"
            exit 1
            ;;
    esac
}

# Configure Ollama AI
configure_ollama() {
    print_header "Ollama AI Configuration"
    
    read -p "Do you want to enable AI features (Ollama)? (y/n) [y]: " ENABLE_AI
    ENABLE_AI=${ENABLE_AI:-y}
    
    if [[ $ENABLE_AI =~ ^[Yy]$ ]]; then
        echo "How do you want to run Ollama?"
        echo "1) Self-hosted in Docker (recommended)"
        echo "2) External Ollama server"
        read -p "Enter your choice (1-2) [1]: " OLLAMA_CHOICE
        OLLAMA_CHOICE=${OLLAMA_CHOICE:-1}
        
        case $OLLAMA_CHOICE in
            1)
                USE_DOCKER_OLLAMA=true
                read -p "Ollama port [11434]: " OLLAMA_PORT
                OLLAMA_PORT=${OLLAMA_PORT:-11434}
                OLLAMA_BASE_URL="http://ollama:11434"
                
                read -p "Pull models on startup? (y/n) [y]: " PULL_MODELS
                PULL_MODELS=${PULL_MODELS:-y}
                
                if [[ $PULL_MODELS =~ ^[Yy]$ ]]; then
                    OLLAMA_PULL_MODELS=true
                    read -p "Default model [tinyllama]: " OLLAMA_MODEL
                    OLLAMA_MODEL=${OLLAMA_MODEL:-tinyllama}
                else
                    OLLAMA_PULL_MODELS=false
                fi
                ;;
            2)
                USE_DOCKER_OLLAMA=false
                read -p "Ollama server URL: " OLLAMA_BASE_URL
                ;;
            *)
                print_error "Invalid choice"
                exit 1
                ;;
        esac
    else
        USE_DOCKER_OLLAMA=false
    fi
}

# Configure application settings
configure_app() {
    print_header "Application Configuration"
    
    read -p "Application port [8080]: " APP_PORT
    APP_PORT=${APP_PORT:-8080}
    
    read -p "Enable debug mode? (y/n) [n]: " DEBUG_MODE
    DEBUG_MODE=${DEBUG_MODE:-n}
    if [[ $DEBUG_MODE =~ ^[Yy]$ ]]; then
        DEBUG=true
    else
        DEBUG=false
    fi
    
    read -p "CORS origins (* for all, or comma-separated list) [*]: " CORS_ORIGINS
    CORS_ORIGINS=${CORS_ORIGINS:-*}
    
    # Ask for laboratory type
    echo ""
    echo "What type of laboratory are you running?"
    echo "1) Medical laboratory (Patients)"
    echo "2) Non-medical laboratory (Customers)"
    read -p "Enter your choice (1-2) [1]: " LAB_TYPE_CHOICE
    LAB_TYPE_CHOICE=${LAB_TYPE_CHOICE:-1}
    
    case $LAB_TYPE_CHOICE in
        1)
            MEDICAL_MODE=true
            print_info "Using medical mode (Patient terminology)"
            ;;
        2)
            MEDICAL_MODE=false
            print_info "Using non-medical mode (Customer terminology)"
            ;;
        *)
            print_warning "Invalid choice, defaulting to medical mode"
            MEDICAL_MODE=true
            ;;
    esac
    
    # Generate SECRET_KEY
    print_info "Generating secure SECRET_KEY..."
    SECRET_KEY=$(generate_secret_key)
    print_success "SECRET_KEY generated"
}

# Generate .env file
generate_env_file() {
    print_header "Generating Configuration File"
    
    # Build COMPOSE_PROFILES
    COMPOSE_PROFILES=""
    if [[ $USE_DOCKER_POSTGRES == true ]]; then
        COMPOSE_PROFILES="postgres"
    fi
    if [[ $ENABLE_BACKUP =~ ^[Yy]$ ]] && [[ $USE_DOCKER_POSTGRES == true ]]; then
        if [ -n "$COMPOSE_PROFILES" ]; then
            COMPOSE_PROFILES="${COMPOSE_PROFILES},backup"
        else
            COMPOSE_PROFILES="backup"
        fi
    fi
    if [[ $USE_DOCKER_OLLAMA == true ]]; then
        if [ -n "$COMPOSE_PROFILES" ]; then
            COMPOSE_PROFILES="${COMPOSE_PROFILES},ai"
        else
            COMPOSE_PROFILES="ai"
        fi
    fi
    
    # Backup existing .env
    if [ -f "$ENV_FILE" ]; then
        BACKUP_FILE="${ENV_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
        cp "$ENV_FILE" "$BACKUP_FILE"
        print_warning "Existing .env backed up to $BACKUP_FILE"
    fi
    
    # Create .env file
    cat > "$ENV_FILE" <<EOF
# LabAdmin Docker Configuration
# Generated on $(date)

# ==============================================================================
# DEPLOYMENT MODE
# ==============================================================================
COMPOSE_PROFILES=${COMPOSE_PROFILES}

# ==============================================================================
# APPLICATION SETTINGS
# ==============================================================================
APP_NAME=LabAdmin
APP_VERSION=0.1.0
DEBUG=${DEBUG}
APP_CONTAINER_NAME=labadmin-app
APP_HOST_PORT=${APP_PORT}
RESTART_POLICY=unless-stopped
APP_LOGS_DIR=./logs

# ==============================================================================
# DATABASE CONFIGURATION
# ==============================================================================
DATABASE_URL=${DATABASE_URL}
EOF

    if [[ $USE_DOCKER_POSTGRES == true ]]; then
        cat >> "$ENV_FILE" <<EOF

# PostgreSQL Docker Settings
POSTGRES_VERSION=16-alpine
POSTGRES_CONTAINER_NAME=labadmin-postgres
POSTGRES_HOST=postgres
POSTGRES_DB=${POSTGRES_DB}
POSTGRES_USER=${POSTGRES_USER}
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
POSTGRES_HOST_PORT=${POSTGRES_PORT}
EOF
    fi

    cat >> "$ENV_FILE" <<EOF

# ==============================================================================
# POSTGRESQL BACKUP CONFIGURATION
# ==============================================================================
POSTGRES_BACKUP_CONTAINER_NAME=labadmin-postgres-backup
BACKUP_RETENTION_DAYS=7
BACKUP_CRON_SCHEDULE=0 * * * *

# ==============================================================================
# JWT AUTHENTICATION
# ==============================================================================
SECRET_KEY=${SECRET_KEY}
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# ==============================================================================
# CORS SETTINGS
# ==============================================================================
CORS_ORIGINS=${CORS_ORIGINS}

# ==============================================================================
# FRONTEND URL
# ==============================================================================
FRONTEND_URL=http://localhost:${APP_PORT}

# ==============================================================================
# FILE UPLOAD SETTINGS
# ==============================================================================
MAX_UPLOAD_SIZE_MB=10
ALLOWED_IMAGE_TYPES=image/jpeg,image/png

# ==============================================================================
# MODE CONFIGURATION
# ==============================================================================
MEDICAL_MODE=${MEDICAL_MODE}
EOF

    if [[ $USE_DOCKER_OLLAMA == true ]]; then
        cat >> "$ENV_FILE" <<EOF

# ==============================================================================
# OLLAMA AI CONFIGURATION
# ==============================================================================
OLLAMA_IMAGE=ollama/ollama:latest
OLLAMA_CONTAINER_NAME=labadmin-ollama
OLLAMA_HOST_PORT=${OLLAMA_PORT}
OLLAMA_ORIGINS=*
OLLAMA_HOST_INTERNAL=0.0.0.0
OLLAMA_BASE_URL=${OLLAMA_BASE_URL}
OLLAMA_PULL_MODELS=${OLLAMA_PULL_MODELS:-false}
OLLAMA_DEFAULT_MODEL=${OLLAMA_MODEL:-tinyllama}
OLLAMA_PULL_ADDITIONAL=true
EOF
    elif [[ $ENABLE_AI =~ ^[Yy]$ ]]; then
        cat >> "$ENV_FILE" <<EOF

# ==============================================================================
# OLLAMA AI CONFIGURATION
# ==============================================================================
OLLAMA_BASE_URL=${OLLAMA_BASE_URL}
EOF
    fi

    cat >> "$ENV_FILE" <<EOF

# ==============================================================================
# MICROSOFT OAUTH (OPTIONAL)
# ==============================================================================
MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=
MICROSOFT_TENANT_ID=common
MICROSOFT_REDIRECT_URI=

# ==============================================================================
# LICENSE SERVER
# Please contact LabAdmin support if you have special licensing requirements or want to host your own license server.
# A deactivation of the license server is not allowed without previous agreement with LabAdmin Support.
# ==============================================================================
LICENSE_SERVER_URL=https://license.labadmin.de
LICENSE_SERVER_ENABLED=true
EOF

    print_success "Configuration file created: $ENV_FILE"
}

# Generate docker-compose.yml for production deployment
generate_compose_file() {
    if [ "$DEPLOYMENT_MODE" = "production" ] && [ ! -f "$COMPOSE_FILE" ]; then
        print_header "Generating Docker Compose Configuration"
        
        cat > "$COMPOSE_FILE" <<'EOF'
services:
  # PostgreSQL Database
  postgres:
    image: postgres:16-alpine
    container_name: ${POSTGRES_CONTAINER_NAME:-labadmin-postgres}
    profiles:
      - postgres
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-labadmin}
      POSTGRES_USER: ${POSTGRES_USER:-labadmin}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-labadmin123}
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - postgres_backups:/backups
    ports:
      - "${POSTGRES_HOST_PORT:-5432}:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-labadmin}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - labadmin-network
    restart: ${RESTART_POLICY:-unless-stopped}

  # PostgreSQL Backup Service
  postgres-backup:
    image: postgres:16-alpine
    container_name: ${POSTGRES_BACKUP_CONTAINER_NAME:-labadmin-postgres-backup}
    profiles:
      - postgres
      - backup
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-labadmin}
      POSTGRES_USER: ${POSTGRES_USER:-labadmin}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-labadmin123}
      POSTGRES_HOST: ${POSTGRES_HOST:-postgres}
      BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-7}
    volumes:
      - postgres_backups:/backups
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - labadmin-network
    restart: ${RESTART_POLICY:-unless-stopped}
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        apk add --no-cache dcron
        echo '${BACKUP_CRON_SCHEDULE:-0 * * * *} PGPASSWORD=$POSTGRES_PASSWORD pg_dump -h $POSTGRES_HOST -U $POSTGRES_USER -d $POSTGRES_DB | gzip > /backups/backup_$(date +\%Y\%m\%d_\%H\%M\%S).sql.gz && find /backups -name "backup_*.sql.gz" -mtime +$BACKUP_RETENTION_DAYS -delete' > /etc/crontabs/root
        crond -f -l 2

  # Ollama AI Service
  ollama:
    image: ${OLLAMA_IMAGE:-ollama/ollama:latest}
    container_name: ${OLLAMA_CONTAINER_NAME:-labadmin-ollama}
    profiles:
      - ai
    volumes:
      - ollama:/root/.ollama
    ports:
      - "${OLLAMA_HOST_PORT:-11434}:11434"
    networks:
      - labadmin-network
    restart: ${RESTART_POLICY:-unless-stopped}
    environment: 
      OLLAMA_ORIGINS: ${OLLAMA_ORIGINS:-*}
      OLLAMA_HOST: ${OLLAMA_HOST_INTERNAL:-0.0.0.0}
    healthcheck:
      test: ["CMD", "ollama", "list"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 300s
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        /bin/ollama serve &
        pid=$$!
        sleep 5
        if [ "${OLLAMA_PULL_MODELS:-true}" = "true" ]; then
          echo "Pulling default model: ${OLLAMA_DEFAULT_MODEL:-tinyllama}..."
          ollama pull ${OLLAMA_DEFAULT_MODEL:-tinyllama}
          if [ "${OLLAMA_PULL_ADDITIONAL:-true}" = "true" ]; then
            echo "Pulling additional models..."
            ollama pull llama3.2:1b
          fi
        fi
        wait $$pid

  # LabAdmin Application
  app:
    image: ghcr.io/labadmin-software/labadmin:latest
    container_name: ${APP_CONTAINER_NAME:-labadmin-app}
    ports:
      - "${APP_HOST_PORT:-8080}:8080"
    environment:
      APP_NAME: ${APP_NAME:-LabAdmin}
      APP_VERSION: ${APP_VERSION:-0.1.0}
      DEBUG: ${DEBUG:-false}
      DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://labadmin:labadmin123@postgres:5432/labadmin}
      SECRET_KEY: ${SECRET_KEY:-change-this-secret-key-in-production}
      ALGORITHM: ${ALGORITHM:-HS256}
      ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-30}
      CORS_ORIGINS: ${CORS_ORIGINS:-*}
      FRONTEND_URL: ${FRONTEND_URL:-http://localhost:8080}
      MAX_UPLOAD_SIZE_MB: ${MAX_UPLOAD_SIZE_MB:-10}
      ALLOWED_IMAGE_TYPES: ${ALLOWED_IMAGE_TYPES:-image/jpeg,image/png}
      MEDICAL_MODE: ${MEDICAL_MODE:-true}
      OLLAMA_BASE_URL: ${OLLAMA_BASE_URL:-http://ollama:11434}
      MICROSOFT_CLIENT_ID: ${MICROSOFT_CLIENT_ID:-}
      MICROSOFT_CLIENT_SECRET: ${MICROSOFT_CLIENT_SECRET:-}
      MICROSOFT_TENANT_ID: ${MICROSOFT_TENANT_ID:-common}
      MICROSOFT_REDIRECT_URI: ${MICROSOFT_REDIRECT_URI:-}
      LICENSE_SERVER_URL: ${LICENSE_SERVER_URL:-https://license.labadmin.de}
      LICENSE_SERVER_ENABLED: ${LICENSE_SERVER_ENABLED:-true}
    volumes:
      - app_data:/app/data
      - ${APP_LOGS_DIR:-./logs}:/app/logs
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 60s
    networks:
      - labadmin-network
    restart: ${RESTART_POLICY:-unless-stopped}

volumes:
  postgres_data:
    driver: local
  postgres_backups:
    driver: local
  ollama:
    driver: local
  app_data:
    driver: local

networks:
  labadmin-network:
    driver: bridge
EOF
        
        print_success "Docker Compose configuration created: $COMPOSE_FILE"
    fi
}

# Check for existing containers and volumes
check_existing_deployment() {
    print_header "Checking Existing Deployment"
    
    # Check if any LabAdmin containers are running
    EXISTING_CONTAINERS=$(docker ps -a --filter "name=labadmin" --format "{{.Names}}" 2>/dev/null || true)
    
    if [ -n "$EXISTING_CONTAINERS" ]; then
        print_warning "Found existing LabAdmin containers:"
        echo "$EXISTING_CONTAINERS"
        echo ""
        print_warning "⚠️  IMPORTANT: If you changed PostgreSQL credentials, the existing database"
        print_warning "    will NOT accept the new password. You must recreate the containers."
        echo ""
        read -p "Do you want to stop and remove existing containers? (y/n) [y]: " REMOVE_CONTAINERS
        REMOVE_CONTAINERS=${REMOVE_CONTAINERS:-y}
        
        if [[ $REMOVE_CONTAINERS =~ ^[Yy]$ ]]; then
            print_info "Stopping and removing existing containers..."
            docker compose down
            
            # Ask about volumes
            echo ""
            print_warning "⚠️  Do you also want to remove data volumes (PostgreSQL data, backups, etc.)?"
            print_warning "    Choose 'y' if you want a fresh start or changed PostgreSQL password."
            print_warning "    Choose 'n' to keep existing data (only if credentials haven't changed)."
            read -p "Remove volumes? (y/n) [n]: " REMOVE_VOLUMES
            REMOVE_VOLUMES=${REMOVE_VOLUMES:-n}
            
            if [[ $REMOVE_VOLUMES =~ ^[Yy]$ ]]; then
                print_warning "Removing volumes and all data..."
                docker compose down -v
                print_success "Containers and volumes removed"
            else
                print_success "Containers removed, volumes preserved"
            fi
        else
            print_info "Keeping existing containers"
            echo ""
            print_warning "Note: If you changed credentials, you may encounter authentication errors."
            print_warning "      Run 'docker compose down -v' to remove everything and start fresh."
        fi
        echo ""
    else
        print_success "No existing LabAdmin containers found"
    fi
}

# Display summary and start services
start_services() {
    print_header "Configuration Summary"
    
    echo "Database: $(if [[ $USE_DOCKER_POSTGRES == true ]]; then echo "Self-hosted PostgreSQL in Docker"; else echo "External PostgreSQL"; fi)"
    if [[ $USE_DOCKER_POSTGRES == true ]]; then
        echo "  - Database: $POSTGRES_DB"
        echo "  - User: $POSTGRES_USER"
        echo "  - Port: $POSTGRES_PORT"
        echo "  - Backup: $(if [[ $ENABLE_BACKUP =~ ^[Yy]$ ]]; then echo "Enabled"; else echo "Disabled"; fi)"
    fi
    echo ""
    echo "AI: $(if [[ $ENABLE_AI =~ ^[Yy]$ ]]; then echo "Enabled"; else echo "Disabled"; fi)"
    if [[ $USE_DOCKER_OLLAMA == true ]]; then
        echo "  - Mode: Self-hosted in Docker"
        echo "  - Port: $OLLAMA_PORT"
        echo "  - Model: $OLLAMA_MODEL"
    elif [[ $ENABLE_AI =~ ^[Yy]$ ]]; then
        echo "  - Mode: External server"
        echo "  - URL: $OLLAMA_BASE_URL"
    fi
    echo ""
    echo "Application:"
    echo "  - Port: $APP_PORT"
    echo "  - Debug: $DEBUG"
    echo "  - Laboratory Type: $(if [[ $MEDICAL_MODE == true ]]; then echo "Medical (Patients)"; else echo "Non-medical (Customers)"; fi)"
    echo "  - URL: http://localhost:$APP_PORT"
    echo ""
    echo "Profiles: $COMPOSE_PROFILES"
    echo ""
    
    # Check for existing deployment
    check_existing_deployment
    
    # Generate docker-compose.yml if needed
    generate_compose_file
    
    read -p "Start LabAdmin now? (y/n) [y]: " START_NOW
    START_NOW=${START_NOW:-y}
    
    if [[ $START_NOW =~ ^[Yy]$ ]]; then
        print_header "Starting LabAdmin"
        
        if [ "$DEPLOYMENT_MODE" = "production" ]; then
            print_info "Pulling LabAdmin image from GitHub Container Registry..."
            docker pull $DOCKER_IMAGE
        else
            print_info "Building LabAdmin from source..."
            docker compose build
        fi
        
        print_info "Starting services (this will pull any needed images)..."
        docker compose up -d
        
        print_success "LabAdmin is starting!"
        echo ""
        print_info "Checking service status..."
        sleep 5
        docker compose ps
        
        echo ""
        print_info "Waiting for services to be healthy..."
        sleep 10
        
        # Check for errors in logs
        if docker compose logs app 2>&1 | grep -i "error\|failed\|exception" > /dev/null; then
            print_warning "Detected potential errors in application logs"
            echo ""
            echo "Recent application logs:"
            docker compose logs --tail=20 app
            echo ""
            print_warning "If you see password authentication errors, run:"
            print_warning "  docker compose down -v"
            print_warning "  docker compose up -d"
            echo ""
        fi
        
        print_success "Setup complete!"
        echo ""
        echo "Access LabAdmin at: http://localhost:$APP_PORT"
        echo ""
        echo "Default login credentials:"
        echo "  - Username: admin"
        echo "  - Password: password"
        echo ""
        echo "Useful commands:"
        echo "  - View logs:           docker compose logs -f"
        echo "  - View app logs:       docker compose logs -f app"
        echo "  - Stop services:       docker compose down"
        echo "  - Reset everything:    docker compose down -v && docker compose up -d"
        echo "  - Restart services:    docker compose restart"
        echo "  - View status:         docker compose ps"
        echo ""
    else
        print_success "Setup complete!"
        echo ""
        echo "To start LabAdmin manually, run:"
        echo "  docker compose up -d"
        echo ""
    fi
}

# Main script
main() {
    clear
    print_header "LabAdmin Docker Setup"
    
    if [ "$DEPLOYMENT_MODE" = "production" ]; then
        print_info "Running in PRODUCTION mode (using pre-built Docker image)"
        print_info "Image: $DOCKER_IMAGE"
    else
        print_info "Running in DEVELOPMENT mode (building from source)"
    fi
    echo ""
    
    echo "This script will help you set up LabAdmin with Docker."
    echo "It will:"
    echo "  1. Check/install Docker and Docker Compose"
    echo "  2. Configure PostgreSQL (self-hosted or external)"
    echo "  3. Configure Ollama AI (optional)"
    echo "  4. Generate secure SECRET_KEY"
    echo "  5. Create .env configuration file"
    if [ "$DEPLOYMENT_MODE" = "production" ]; then
        echo "  6. Create docker-compose.yml (if needed)"
        echo "  7. Pull LabAdmin image and start services"
    else
        echo "  6. Build and start LabAdmin services"
    fi
    echo ""
    read -p "Press Enter to continue or Ctrl+C to cancel..."
    
    # Check prerequisites
    check_docker
    check_docker_compose
    
    # Configure services
    configure_postgres
    configure_ollama
    configure_app
    
    # Generate configuration
    generate_env_file
    
    # Start services
    start_services
}

# Run main function
main
