#!/usr/bin/env bash

# Check status of Docker resources and auto-cleanup service

set -euo pipefail

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

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"
}

echo "=== FetchML Cleanup Status ==="
echo ""

# Docker resources
log_info "Docker Resources:"
containers=$(docker ps -a --filter "name=ml-" --format "{{.Names}}" | wc -l | tr -d ' ')
images=$(docker images --filter "reference=fetch_ml-*" --format "{{.Repository}}" | wc -l | tr -d ' ')
networks=$(docker network ls --filter "name=ml-" --format "{{.Name}}" | wc -l | tr -d ' ')
volumes=$(docker volume ls --filter "name=ml-" --format "{{.Name}}" | wc -l | tr -d ' ')

echo "  Containers: $containers"
echo "  Images: $images"
echo "  Networks: $networks"
echo "  Volumes: $volumes"

if [ "$containers" -gt 0 ]; then
    echo ""
    log_info "Active containers:"
    docker ps --filter "name=ml-" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
fi

# Auto-cleanup service status
echo ""
log_info "Auto-cleanup Service:"

if [[ "$OSTYPE" == "darwin"* ]]; then
    if launchctl list | grep -q "com.fetchml.cleanup"; then
        log_success "Auto-cleanup service is running"
        echo "  Logs: /tmp/fetchml-cleanup.log"
        echo "  To check logs: tail -f /tmp/fetchml-cleanup.log"
    else
        log_warning "Auto-cleanup service is not installed"
        echo "  To install: make auto-cleanup"
    fi
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    if systemctl is-active --quiet auto-cleanup.timer; then
        log_success "Auto-cleanup timer is active"
        echo "  Status: systemctl status auto-cleanup.timer"
        echo "  Logs: journalctl -u auto-cleanup.service"
    else
        log_warning "Auto-cleanup timer is not active"
        echo "  To install: make auto-cleanup"
    fi
fi

# Disk usage
echo ""
log_info "Docker Disk Usage:"
docker system df --format "table {{.Type}}\t{{.TotalCount}}\t{{.Size}}\t{{.Reclaimable}}"

# Quick cleanup suggestion
echo ""
if [ "$containers" -gt 0 ] || [ "$images" -gt 0 ] || [ "$networks" -gt 0 ] || [ "$volumes" -gt 0 ]; then
    log_warning "Resources found that can be cleaned up"
    echo "  Quick cleanup: make self-cleanup"
    echo "  Force cleanup: make self-cleanup --force"
    echo "  Full cleanup: make self-cleanup --all"
else
    log_success "No fetch_ml resources found - system is clean!"
fi

echo ""
echo "=== Cleanup Commands ==="
echo "  make self-cleanup           - Interactive cleanup"
echo "  ./scripts/cleanup.sh --dry-run - Preview what would be cleaned"
echo "  ./scripts/cleanup.sh --force - Force cleanup without prompts"
echo "  ./scripts/cleanup.sh --all   - Clean everything including images"
