#!/bin/bash
# Module 17: Complete Setup Script
# setup-module17.sh

set -e  # Exit on error

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

# Banner
echo -e "${BLUE}"
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     Module 17: GitHub Models and AI Integration Setup        ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Function to check command existence
check_command() {
    if command -v $1 &> /dev/null; then
        echo -e "${GREEN}✓${NC} $1 is installed"
        return 0
    else
        echo -e "${RED}✗${NC} $1 is not installed"
        return 1
    fi
}

# Function to check environment variable
check_env_var() {
    if [ -z "${!1}" ]; then
        echo -e "${RED}✗${NC} $1 is not set"
        return 1
    else
        echo -e "${GREEN}✓${NC} $1 is configured"
        return 0
    fi
}

# Function to create directory if not exists
create_dir() {
    if [ ! -d "$1" ]; then
        mkdir -p "$1"
        echo -e "${GREEN}✓${NC} Created directory: $1"
    fi
}

# Step 1: Check prerequisites
echo -e "\n${YELLOW}Step 1: Checking prerequisites...${NC}"
echo "=================================="

PREREQ_MET=true

# Check required commands
for cmd in python3 pip docker git curl jq; do
    check_command $cmd || PREREQ_MET=false
done

# Check Python version
PYTHON_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
if (( $(echo "$PYTHON_VERSION >= 3.11" | bc -l) )); then
    echo -e "${GREEN}✓${NC} Python $PYTHON_VERSION (>= 3.11 required)"
else
    echo -e "${RED}✗${NC} Python $PYTHON_VERSION (>= 3.11 required)"
    PREREQ_MET=false
fi

# Check Docker daemon
if docker info &> /dev/null; then
    echo -e "${GREEN}✓${NC} Docker daemon is running"
else
    echo -e "${RED}✗${NC} Docker daemon is not running"
    PREREQ_MET=false
fi

if [ "$PREREQ_MET" = false ]; then
    echo -e "\n${RED}Some prerequisites are missing. Please install them first.${NC}"
    exit 1
fi

# Step 2: Setup directory structure
echo -e "\n${YELLOW}Step 2: Setting up directory structure...${NC}"
echo "========================================="

# Create all necessary directories
directories=(
    "exercises/exercise1-foundation/data"
    "exercises/exercise1-foundation/tests"
    "exercises/exercise2-application/data/documents"
    "exercises/exercise2-application/data/processed"
    "exercises/exercise2-application/tests"
    "exercises/exercise3-mastery/models"
    "exercises/exercise3-mastery/deployment"
    "exercises/exercise3-mastery/tests"
    "monitoring/prometheus"
    "monitoring/grafana/dashboards"
    "monitoring/grafana/provisioning"
    "notebooks"
    "logs"
    "data/documents"
    "data/embeddings"
)

for dir in "${directories[@]}"; do
    create_dir "$dir"
done

# Step 3: Setup Python environment
echo -e "\n${YELLOW}Step 3: Setting up Python environment...${NC}"
echo "========================================"

# Create virtual environment if not exists
if [ ! -d "venv" ]; then
    echo "Creating virtual environment..."
    python3 -m venv venv
    echo -e "${GREEN}✓${NC} Virtual environment created"
fi

# Activate virtual environment
source venv/bin/activate
echo -e "${GREEN}✓${NC} Virtual environment activated"

# Upgrade pip
pip install --quiet --upgrade pip
echo -e "${GREEN}✓${NC} pip upgraded"

# Install requirements
if [ -f "requirements.txt" ]; then
    echo "Installing Python packages..."
    pip install --quiet -r requirements.txt
    echo -e "${GREEN}✓${NC} Python packages installed"
else
    echo -e "${YELLOW}⚠${NC} requirements.txt not found, creating it..."
    cat > requirements.txt << 'EOF'
# Core AI/ML packages
openai==1.3.0
langchain==0.0.350
semantic-kernel==0.4.0
tiktoken==0.5.2
numpy==1.26.2
pandas==2.1.4

# Vector databases and search
chromadb==0.4.22
qdrant-client==1.7.0
faiss-cpu==1.7.4
azure-search-documents==11.4.0

# API and web frameworks
fastapi==0.104.1
uvicorn[standard]==0.24.0
streamlit==1.29.0

# Azure integration
azure-identity==1.15.0
azure-storage-blob==12.19.0
azure-cosmos==4.5.1

# Utilities
python-dotenv==1.0.0
pydantic==2.5.0
httpx==0.25.2
tenacity==8.2.3
redis==5.0.1

# Testing
pytest==7.4.3
pytest-asyncio==0.21.1
pytest-benchmark==4.0.0
locust==2.17.0

# Monitoring
prometheus-client==0.19.0
opentelemetry-api==1.21.0
opentelemetry-sdk==1.21.0
opentelemetry-instrumentation-fastapi==0.42b0
EOF
    pip install --quiet -r requirements.txt
    echo -e "${GREEN}✓${NC} Requirements file created and packages installed"
fi

# Step 4: Check environment variables
echo -e "\n${YELLOW}Step 4: Checking environment configuration...${NC}"
echo "============================================="

ENV_COMPLETE=true

# Check required environment variables
env_vars=(
    "GITHUB_TOKEN"
    "AZURE_OPENAI_ENDPOINT"
    "AZURE_OPENAI_API_KEY"
)

for var in "${env_vars[@]}"; do
    check_env_var $var || ENV_COMPLETE=false
done

# Create .env file if not exists
if [ ! -f ".env" ]; then
    echo -e "\n${YELLOW}Creating .env file...${NC}"
    cat > .env << 'EOF'
# GitHub Models
GITHUB_TOKEN=your_github_token_here
GITHUB_MODELS_ENDPOINT=https://models.inference.ai.azure.com

# Azure OpenAI
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_API_KEY=your_api_key_here
AZURE_OPENAI_API_VERSION=2023-12-01-preview
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4
AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT=text-embedding-ada-002

# Azure AI Search
AZURE_SEARCH_ENDPOINT=https://your-search-service.search.windows.net
AZURE_SEARCH_KEY=your_admin_key_here
AZURE_SEARCH_INDEX_NAME=module17-vectors

# Application Settings
EMBEDDING_MODEL=text-embedding-ada-002
CHUNK_SIZE=1000
CHUNK_OVERLAP=200
VECTOR_DIMENSION=1536
CACHE_TTL_SECONDS=3600

# Monitoring
LOG_LEVEL=INFO
EOF
    echo -e "${GREEN}✓${NC} .env file created"
    echo -e "${YELLOW}⚠${NC} Please edit .env file with your actual credentials"
    ENV_COMPLETE=false
fi

# Step 5: Setup Docker services
echo -e "\n${YELLOW}Step 5: Setting up Docker services...${NC}"
echo "====================================="

# Check if docker-compose.yml exists
if [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}✗${NC} docker-compose.yml not found"
    echo "Please ensure you have the docker-compose.yml file in the current directory"
    exit 1
fi

# Start Docker services
echo "Starting Docker services..."
docker-compose up -d

# Wait for services to be ready
echo -e "\n${YELLOW}Waiting for services to be ready...${NC}"
sleep 10

# Check service health
echo -e "\n${YELLOW}Checking service health...${NC}"

# Check Qdrant
if curl -s http://localhost:6333/health | jq -e '.status == "ok"' > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Qdrant is healthy"
else
    echo -e "${RED}✗${NC} Qdrant is not responding"
fi

# Check Redis
if docker exec module17-redis redis-cli ping | grep -q PONG; then
    echo -e "${GREEN}✓${NC} Redis is healthy"
else
    echo -e "${RED}✗${NC} Redis is not responding"
fi

# Check PostgreSQL
if docker exec module17-postgres pg_isready -U workshop | grep -q "accepting connections"; then
    echo -e "${GREEN}✓${NC} PostgreSQL is healthy"
else
    echo -e "${RED}✗${NC} PostgreSQL is not responding"
fi

# Step 6: Create sample data
echo -e "\n${YELLOW}Step 6: Creating sample data...${NC}"
echo "================================"

# Create sample products.json
cat > exercises/exercise1-foundation/data/products.json << 'EOF'
[
  {
    "id": "prod-001",
    "name": "AI-Powered Smart Camera",
    "description": "Advanced security camera with real-time object detection and facial recognition capabilities",
    "category": "Electronics",
    "price": 299.99,
    "features": ["4K resolution", "Night vision", "Motion detection", "Cloud storage", "Mobile app", "AI alerts"]
  },
  {
    "id": "prod-002",
    "name": "Quantum Computing Textbook",
    "description": "Comprehensive guide to quantum computing principles and practical applications",
    "category": "Books",
    "price": 89.99,
    "features": ["Beginner friendly", "Code examples", "Online resources", "Practice problems"]
  }
]
EOF
echo -e "${GREEN}✓${NC} Sample data created"

# Step 7: Run verification script
echo -e "\n${YELLOW}Step 7: Running verification...${NC}"
echo "================================"

# Create and run verification script
cat > verify-setup.py << 'EOF'
#!/usr/bin/env python3
import sys
import os
import httpx
import asyncio
from rich.console import Console
from rich.table import Table
from dotenv import load_dotenv

console = Console()
load_dotenv()

async def main():
    table = Table(title="Module 17 Setup Verification")
    table.add_column("Component", style="cyan")
    table.add_column("Status", style="green")
    
    # Check environment variables
    env_vars = ["GITHUB_TOKEN", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_API_KEY"]
    all_env_set = True
    for var in env_vars:
        if os.getenv(var) and os.getenv(var) != f"your_{var.lower()}_here":
            table.add_row(f"Env: {var}", "✓ Configured")
        else:
            table.add_row(f"Env: {var}", "✗ Not configured")
            all_env_set = False
    
    # Check services
    try:
        async with httpx.AsyncClient() as client:
            # Qdrant
            try:
                resp = await client.get("http://localhost:6333/health")
                if resp.status_code == 200:
                    table.add_row("Qdrant", "✓ Running")
                else:
                    table.add_row("Qdrant", "✗ Unhealthy")
            except:
                table.add_row("Qdrant", "✗ Not accessible")
    except:
        table.add_row("Services", "✗ Connection error")
    
    console.print(table)
    
    if not all_env_set:
        console.print("\n[yellow]⚠ Please configure your environment variables in .env file[/yellow]")
        return 1
    
    return 0

if __name__ == "__main__":
    exit_code = asyncio.run(main())
    sys.exit(exit_code)
EOF

python verify-setup.py

# Step 8: Final instructions
echo -e "\n${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                    Setup Complete! 🎉                        ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

echo -e "\n${GREEN}Next Steps:${NC}"
echo "1. Edit the .env file with your actual API credentials"
echo "2. Verify all services are running: docker-compose ps"
echo "3. Access service UIs:"
echo "   - Grafana: http://localhost:3000 (admin/admin)"
echo "   - Prometheus: http://localhost:9090"
echo "   - Jaeger: http://localhost:16686"
echo ""
echo "4. Start with Exercise 1:"
echo "   cd exercises/exercise1-foundation"
echo "   python app.py"
echo ""
echo "5. Or launch Jupyter for experimentation:"
echo "   docker-compose logs jupyter | grep token"
echo ""

if [ "$ENV_COMPLETE" = false ]; then
    echo -e "\n${YELLOW}⚠ Important: Don't forget to configure your API keys in the .env file!${NC}"
fi

echo -e "\n${GREEN}Happy learning! 🚀${NC}"

# Deactivate virtual environment
deactivate 2>/dev/null || true