#!/bin/bash

# Monitoring Infrastructure Status Script
# This script checks the status of all monitoring components

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

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

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

echo "🔍 Portfolio Tracker - Monitoring Infrastructure Status"
echo "=================================================="

# Check if monitoring services are running
print_status "Checking monitoring services..."

services=("portfolio-elasticsearch" "portfolio-logstash" "portfolio-kibana" "portfolio-filebeat" "portfolio-prometheus" "portfolio-grafana")
all_running=true

for service in "${services[@]}"; do
    if docker ps --format "table {{.Names}}" | grep -q "^$service$"; then
        print_success "$service is running"
    else
        print_error "$service is not running"
        all_running=false
    fi
done

echo ""

# Check service health endpoints
print_status "Checking service health endpoints..."

health_checks=(
    "Elasticsearch:http://localhost:9200/_cluster/health"
    "Kibana:http://localhost:5601/api/status"
    "Prometheus:http://localhost:9090/-/healthy"
    "Grafana:http://localhost:3001/api/health"
)

for check in "${health_checks[@]}"; do
    service_name=$(echo $check | cut -d: -f1)
    url=$(echo $check | cut -d: -f2-)
    
    if curl -s -f "$url" > /dev/null 2>&1; then
        print_success "$service_name health check passed"
    else
        print_error "$service_name health check failed"
        all_running=false
    fi
done

echo ""

# Check application service endpoints (if running)
print_status "Checking application service monitoring endpoints..."

app_services=(
    "User Service:http://localhost:3001"
    "Task Service:http://localhost:3002"
    "Analytics Service:http://localhost:3003"
    "Diagram Service:http://localhost:3004"
    "API Gateway:http://localhost:3000"
)

for service in "${app_services[@]}"; do
    service_name=$(echo $service | cut -d: -f1)
    base_url=$(echo $service | cut -d: -f2-)
    
    # Check health endpoint
    if curl -s -f "$base_url/health" > /dev/null 2>&1; then
        print_success "$service_name /health endpoint is accessible"
    else
        print_warning "$service_name /health endpoint is not accessible (service may not be running)"
    fi
    
    # Check metrics endpoint
    if curl -s -f "$base_url/metrics" > /dev/null 2>&1; then
        print_success "$service_name /metrics endpoint is accessible"
    else
        print_warning "$service_name /metrics endpoint is not accessible (service may not be running)"
    fi
done

echo ""

# Show access URLs
print_status "Access URLs:"
echo "  📊 Kibana (Logs):      http://localhost:5601"
echo "  📈 Grafana (Metrics):  http://localhost:3001 (admin/admin123)"
echo "  🎯 Prometheus:         http://localhost:9090"
echo "  🔍 Elasticsearch:      http://localhost:9200"

echo ""

# Show service endpoints
print_status "Service Monitoring Endpoints:"
echo "  🏥 Health Checks:      http://localhost:PORT/health"
echo "  📊 Metrics:            http://localhost:PORT/metrics"
echo "  ✅ Readiness:          http://localhost:PORT/health/ready"
echo "  💓 Liveness:           http://localhost:PORT/health/live"

echo ""

# Show log locations
print_status "Log Locations:"
echo "  📁 Service Logs:       docker-compose logs [service-name]"
echo "  📁 Monitoring Logs:    docker-compose -f docker/elk/docker-compose.elk.yml logs [service]"
echo "  📁 Application Logs:   Available in Kibana at http://localhost:5601"

echo ""

# Show useful commands
print_status "Useful Commands:"
echo "  🚀 Start monitoring:   ./scripts/deploy-monitoring.sh"
echo "  🔄 Restart monitoring: docker-compose -f docker/elk/docker-compose.elk.yml restart"
echo "  🛑 Stop monitoring:    docker-compose -f docker/elk/docker-compose.elk.yml down"
echo "  📋 View logs:          docker-compose -f docker/elk/docker-compose.elk.yml logs [service]"
echo "  🧪 Run tests:          npm test --prefix packages/shared-types -- --testPathPattern=logging"

echo ""

if [ "$all_running" = true ]; then
    print_success "All monitoring services are healthy! 🎉"
    exit 0
else
    print_error "Some monitoring services are not running properly. Check the logs for more details."
    echo ""
    print_status "To troubleshoot:"
    echo "  1. Check Docker containers: docker ps -a"
    echo "  2. Check service logs: docker-compose -f docker/elk/docker-compose.elk.yml logs [service]"
    echo "  3. Restart services: docker-compose -f docker/elk/docker-compose.elk.yml restart"
    echo "  4. Redeploy: ./scripts/deploy-monitoring.sh"
    exit 1
fi