#!/bin/bash

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

COMPOSE_FILE="docker-compose.prod.yml"

show_help() {
    echo -e "${BLUE}Dyolink Management Tool${NC}"
    echo ""
    echo "Usage: $0 {start|stop|restart|logs|status|backup|update|cleanup|monitor}"
    echo ""
    echo "Commands:"
    echo "  start      - Start all services"
    echo "  stop       - Stop all services"
    echo "  restart    - Restart all services"
    echo "  logs       - Show logs (add -f to follow)"
    echo "  status     - Show container status"
    echo "  backup     - Backup database"
    echo "  update     - Pull and restart with latest images"
    echo "  cleanup    - Clean old containers/images"
    echo "  monitor    - Show health status"
}

check_compose() {
    if [ ! -f "$COMPOSE_FILE" ]; then
        echo -e "${RED}Error: $COMPOSE_FILE not found${NC}"
        exit 1
    fi
}

case "$1" in
    start)
        check_compose
        echo -e "${GREEN}Starting services...${NC}"
        docker-compose -f $COMPOSE_FILE up -d
        ;;
    stop)
        check_compose
        echo -e "${YELLOW}Stopping services...${NC}"
        docker-compose -f $COMPOSE_FILE down
        ;;
    restart)
        check_compose
        echo -e "${YELLOW}Restarting services...${NC}"
        docker-compose -f $COMPOSE_FILE restart
        ;;
    logs)
        check_compose
        echo -e "${GREEN}Showing logs...${NC}"
        docker-compose -f $COMPOSE_FILE logs ${@:2}
        ;;
    status)
        check_compose
        echo -e "${GREEN}Container Status:${NC}"
        docker-compose -f $COMPOSE_FILE ps
        echo -e "\n${GREEN}Running Containers:${NC}"
        docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep dyolink
        ;;
    backup)
        check_compose
        echo -e "${GREEN}Backing up database...${NC}"
        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        BACKUP_FILE="dyolink_backup_$TIMESTAMP.sql.gz"
        docker-compose -f $COMPOSE_FILE exec -T postgres pg_dumpall -U postgres | gzip > $BACKUP_FILE
        if [ $? -eq 0 ]; then
            SIZE=$(du -h $BACKUP_FILE | cut -f1)
            echo -e "${GREEN}✓ Backup saved: $BACKUP_FILE ($SIZE)${NC}"
        else
            echo -e "${RED}✗ Backup failed${NC}"
        fi
        ;;
    update)
        check_compose
        echo -e "${GREEN}Pulling latest images...${NC}"
        docker-compose -f $COMPOSE_FILE pull
        docker-compose -f $COMPOSE_FILE up -d
        echo -e "${GREEN}✓ Update complete!${NC}"
        ;;
    cleanup)
        echo -e "${YELLOW}Cleaning up Docker resources...${NC}"
        docker container prune -f
        docker image prune -f
        docker volume prune -f
        docker network prune -f
        echo -e "${GREEN}✓ Cleanup complete!${NC}"
        ;;
    monitor)
        check_compose
        echo -e "${GREEN}Health Monitoring:${NC}\n"
        
        SERVICES=("postgres" "backend" "frontend" "nginx")
        ALL_HEALTHY=true
        
        for SERVICE in "${SERVICES[@]}"; do
            STATUS=$(docker-compose -f $COMPOSE_FILE ps $SERVICE 2>/dev/null | tail -1)
            if echo "$STATUS" | grep -q "Up"; then
                echo -e "  ${GREEN}✓${NC} $SERVICE: Running"
            else
                echo -e "  ${RED}✗${NC} $SERVICE: Not running"
                ALL_HEALTHY=false
            fi
        done
        
        echo ""
        DISK=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
        if [ $DISK -gt 80 ]; then
            echo -e "${RED}⚠ Disk usage: ${DISK}%${NC}"
            ALL_HEALTHY=false
        else
            echo -e "${GREEN}✓ Disk usage: ${DISK}%${NC}"
        fi
        
        if [ "$ALL_HEALTHY" = true ]; then
            echo -e "\n${GREEN}✅ All systems operational${NC}"
        else
            echo -e "\n${YELLOW}⚠ Issues detected${NC}"
        fi
        ;;
    *)
        show_help
        exit 1
        ;;
esac