#!/bin/bash

# Deploy Monitoring Infrastructure Script
# This script sets up the complete monitoring and logging infrastructure

set -e

echo "🚀 Deploying Portfolio Tracker Monitoring Infrastructure"

# 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}[SUCCESS]${NC} $1"
}

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

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

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    print_error "Docker is not running. Please start Docker and try again."
    exit 1
fi

# Check if Docker Compose is available
if ! command -v docker-compose &> /dev/null; then
    print_error "Docker Compose is not installed. Please install Docker Compose and try again."
    exit 1
fi

# Create necessary directories
print_status "Creating monitoring directories..."
mkdir -p docker/elk/elasticsearch/data
mkdir -p docker/elk/logstash/templates
mkdir -p docker/elk/kibana/data
mkdir -p docker/elk/filebeat/data
mkdir -p docker/elk/prometheus/data
mkdir -p docker/elk/grafana/data
mkdir -p logs/services

# Set proper permissions for Elasticsearch
print_status "Setting permissions for Elasticsearch..."
sudo chown -R 1000:1000 docker/elk/elasticsearch/data || print_warning "Could not set Elasticsearch permissions. You may need to run with sudo."

# Create Elasticsearch index template
print_status "Creating Elasticsearch index template..."
cat > docker/elk/logstash/templates/portfolio-logs-template.json << 'EOF'
{
  "index_patterns": ["portfolio-logs-*"],
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "index.refresh_interval": "30s"
  },
  "mappings": {
    "properties": {
      "@timestamp": {
        "type": "date"
      },
      "level": {
        "type": "keyword"
      },
      "message": {
        "type": "text",
        "analyzer": "standard"
      },
      "service": {
        "type": "keyword"
      },
      "correlation_id": {
        "type": "keyword"
      },
      "user_id": {
        "type": "keyword"
      },
      "log_level": {
        "type": "keyword"
      },
      "service_name": {
        "type": "keyword"
      },
      "container_name": {
        "type": "keyword"
      },
      "environment": {
        "type": "keyword"
      },
      "cluster": {
        "type": "keyword"
      },
      "error_name": {
        "type": "keyword"
      },
      "error_message": {
        "type": "text"
      },
      "error_stack": {
        "type": "text"
      },
      "app_log": {
        "type": "object",
        "enabled": false
      }
    }
  }
}
EOF

# Build shared-types package first
print_status "Building shared-types package..."
npm run build --prefix packages/shared-types

# Install dependencies for all services
print_status "Installing dependencies for all services..."
services=("user-service" "task-service" "analytics-service" "diagram-service" "api-gateway")

for service in "${services[@]}"; do
    if [ -d "packages/$service" ]; then
        print_status "Installing dependencies for $service..."
        npm install --prefix "packages/$service"
    else
        print_warning "Service directory packages/$service not found, skipping..."
    fi
done

# Start the monitoring infrastructure
print_status "Starting monitoring infrastructure..."
docker-compose -f docker/elk/docker-compose.elk.yml up -d

# Wait for services to be ready
print_status "Waiting for services to start..."
sleep 30

# Check if Elasticsearch is ready
print_status "Checking Elasticsearch health..."
max_attempts=30
attempt=1

while [ $attempt -le $max_attempts ]; do
    if curl -s -f http://localhost:9200/_cluster/health > /dev/null 2>&1; then
        print_success "Elasticsearch is ready!"
        break
    else
        print_status "Waiting for Elasticsearch... (attempt $attempt/$max_attempts)"
        sleep 10
        ((attempt++))
    fi
done

if [ $attempt -gt $max_attempts ]; then
    print_error "Elasticsearch failed to start within the expected time"
    exit 1
fi

# Check if Kibana is ready
print_status "Checking Kibana health..."
max_attempts=30
attempt=1

while [ $attempt -le $max_attempts ]; do
    if curl -s -f http://localhost:5601/api/status > /dev/null 2>&1; then
        print_success "Kibana is ready!"
        break
    else
        print_status "Waiting for Kibana... (attempt $attempt/$max_attempts)"
        sleep 10
        ((attempt++))
    fi
done

if [ $attempt -gt $max_attempts ]; then
    print_error "Kibana failed to start within the expected time"
    exit 1
fi

# Check if Prometheus is ready
print_status "Checking Prometheus health..."
if curl -s -f http://localhost:9090/-/healthy > /dev/null 2>&1; then
    print_success "Prometheus is ready!"
else
    print_warning "Prometheus may not be ready yet. Check http://localhost:9090"
fi

# Check if Grafana is ready
print_status "Checking Grafana health..."
if curl -s -f http://localhost:3001/api/health > /dev/null 2>&1; then
    print_success "Grafana is ready!"
else
    print_warning "Grafana may not be ready yet. Check http://localhost:3001"
fi

# Create Kibana index patterns and dashboards
print_status "Setting up Kibana index patterns..."
sleep 10

# Create index pattern
curl -X POST "localhost:5601/api/saved_objects/index-pattern/portfolio-logs" \
  -H "Content-Type: application/json" \
  -H "kbn-xsrf: true" \
  -d '{
    "attributes": {
      "title": "portfolio-logs-*",
      "timeFieldName": "@timestamp"
    }
  }' > /dev/null 2>&1 || print_warning "Could not create Kibana index pattern automatically"

print_success "Monitoring infrastructure deployment completed!"

echo ""
echo "📊 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 ""
echo "🔍 Next Steps:"
echo "  1. Start your application services"
echo "  2. Check service health endpoints (/health, /health/ready, /health/live)"
echo "  3. View metrics at /metrics endpoints"
echo "  4. Monitor logs in Kibana"
echo "  5. View dashboards in Grafana"
echo ""
echo "🛠️  Troubleshooting:"
echo "  • Check service logs: docker-compose -f docker/elk/docker-compose.elk.yml logs [service]"
echo "  • Restart services: docker-compose -f docker/elk/docker-compose.elk.yml restart"
echo "  • Stop all: docker-compose -f docker/elk/docker-compose.elk.yml down"
echo ""

print_success "Monitoring infrastructure is ready! 🎉"