#!/bin/bash
# ================================================
# Math Platform - Production Stop Script
# ================================================

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

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DOCKER_COMPOSE_FILE="$PROJECT_ROOT/docker-compose.yml"
BACKUP_DIR="$PROJECT_ROOT/docker/backups"

echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}Math Platform - Production Stop${NC}"
echo -e "${BLUE}============================================${NC}"

# Function to backup database before stopping
backup_database() {
    echo -e "${YELLOW}Creating database backup before stopping...${NC}"
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/mathdb_backup_$TIMESTAMP.sql"

    mkdir -p "$BACKUP_DIR"

    if docker ps | grep -q math-postgres; then
        if docker exec math-postgres pg_dump -U mathuser mathdb > "$BACKUP_FILE" 2>/dev/null; then
            if [ -f "$BACKUP_FILE" ] && [ -s "$BACKUP_FILE" ]; then
                echo -e "${GREEN}Backup created: $BACKUP_FILE${NC}"
                gzip "$BACKUP_FILE"
                echo -e "${GREEN}Compressed: ${BACKUP_FILE}.gz${NC}"
            fi
        else
            echo -e "${YELLOW}Database backup failed (database might be empty)${NC}"
        fi
    else
        echo -e "${YELLOW}Database container not running${NC}"
    fi
}

# Function to stop services
stop_services() {
    echo -e "${YELLOW}Stopping services...${NC}"
    docker-compose -f "$DOCKER_COMPOSE_FILE" down
    echo -e "${GREEN}Services stopped${NC}"
}

# Function to stop services and remove volumes
stop_services_clean() {
    echo -e "${YELLOW}Stopping services and removing volumes...${NC}"
    echo -e "${RED}WARNING: This will delete all data!${NC}"
    read -p "Are you sure? (yes/no): " confirm

    if [ "$confirm" = "yes" ]; then
        docker-compose -f "$DOCKER_COMPOSE_FILE" down -v
        echo -e "${GREEN}Services stopped and volumes removed${NC}"
    else
        echo -e "${YELLOW}Operation cancelled${NC}"
    fi
}

# Function to show container status
show_status() {
    echo -e "\n${BLUE}============================================${NC}"
    echo -e "${BLUE}Container Status${NC}"
    echo -e "${BLUE}============================================${NC}"
    docker ps -a | grep math- || echo "No math-platform containers found"
}

# Function to clean up old backups
cleanup_old_backups() {
    echo -e "${YELLOW}Cleaning up old backups (keeping last 10)...${NC}"
    mkdir -p "$BACKUP_DIR"
    ls -t "$BACKUP_DIR"/mathdb_backup_*.sql.gz 2>/dev/null | tail -n +11 | xargs -r rm
    echo -e "${GREEN}Backup cleanup completed${NC}"
}

# Main execution
main() {
    BACKUP=true
    CLEAN=false

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --no-backup)
                BACKUP=false
                shift
                ;;
            --clean)
                CLEAN=true
                shift
                ;;
            *)
                echo -e "${RED}Unknown option: $1${NC}"
                echo "Usage: $0 [--no-backup] [--clean]"
                exit 1
                ;;
        esac
    done

    if [ "$BACKUP" = true ]; then
        backup_database
        cleanup_old_backups
    fi

    if [ "$CLEAN" = true ]; then
        stop_services_clean
    else
        stop_services
    fi

    show_status

    echo -e "\n${GREEN}Math Platform stopped successfully!${NC}"
    echo -e "${YELLOW}Start again with: ./docker/start.sh${NC}"
}

# Run main function
main "$@"
