#!/bin/bash
# =============================================================================
# Aegis Development Initialization Script
# =============================================================================
# This script initializes the Aegis platform for local development.
# For production, use: ./scripts/install.sh
#
# Usage:
#   ./scripts/init.sh
# =============================================================================

set -e

echo "╔═══════════════════════════════════════════════════════════════════════╗"
echo "║                    Aegis - Platform Initialization                     ║"
echo "╚═══════════════════════════════════════════════════════════════════════╝"
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Function to print status
print_status() {
    echo -e "${GREEN}[✓]${NC} $1"
}

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

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

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

# Check if containers are running
if ! docker-compose ps | grep -q "aegis-backend"; then
    print_warning "Containers not running. Starting them now..."
    docker-compose up -d
    echo ""
    echo "Waiting for services to be healthy..."
    sleep 10
fi

# Wait for backend to be ready
echo "Waiting for backend to be ready..."
MAX_RETRIES=30
RETRY_COUNT=0
until curl -s http://localhost:8000/health > /dev/null 2>&1; do
    RETRY_COUNT=$((RETRY_COUNT + 1))
    if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
        print_error "Backend failed to start after $MAX_RETRIES attempts"
        exit 1
    fi
    echo "  Waiting... ($RETRY_COUNT/$MAX_RETRIES)"
    sleep 2
done
print_status "Backend is healthy"

# Run database migrations
echo ""
echo "Running database migrations..."
docker-compose exec -T backend alembic upgrade head
print_status "Migrations completed"

# Seed admin user
echo ""
echo "Seeding admin user..."
docker-compose exec -T backend python -m app.seed 2>/dev/null || print_warning "Admin user may already exist"
print_status "Admin user ready"

# Trigger initial MITRE sync (optional)
echo ""
read -p "Do you want to run initial MITRE ATT&CK sync? (y/N) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Triggering MITRE sync (this may take a minute)..."
    # Get admin token
    TOKEN=$(curl -s -X POST "http://localhost:8000/api/v1/auth/login" \
        -d "username=admin&password=admin123" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
    
    if [ -n "$TOKEN" ]; then
        curl -s -X POST "http://localhost:8000/api/v1/system/sync-mitre" \
            -H "Authorization: Bearer $TOKEN" > /dev/null
        print_status "MITRE sync triggered"
    else
        print_warning "Could not authenticate. Run sync manually from the System page."
    fi
fi

# Print summary
echo ""
echo "╔═══════════════════════════════════════════════════════════════════════╗"
echo "║                     Aegis is ready!                                    ║"
echo "╠═══════════════════════════════════════════════════════════════════════╣"
echo "║                                                                        ║"
echo "║  Frontend:       http://localhost:5173                                 ║"
echo "║  Backend API:    http://localhost:8000                                 ║"
echo "║  Swagger UI:     http://localhost:8000/docs                            ║"
echo "║  MinIO Console:  http://localhost:9001                                 ║"
echo "║                                                                        ║"
echo "║  Default login:  admin / admin123                                      ║"
echo "║                                                                        ║"
echo "║  ⚠️  Change the default password in production!                        ║"
echo "║                                                                        ║"
echo "╚═══════════════════════════════════════════════════════════════════════╝"
echo ""
