#!/bin/bash
# Start MCP-ZERO LLM services with offline-first resilience

set -e

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

# Check if offline mode is active
check_offline_mode() {
  if [ -f "./.mcp/locks/offline.lock" ]; then
    echo -e "${YELLOW}Offline lock file detected, starting in offline mode${NC}"
    export MCP_OFFLINE_MODE=true
    return 0
  fi
  return 1
}

# Start LLM services
start_llm_services() {
  echo -e "${BLUE}Starting MCP-ZERO LLM services...${NC}"
  
  # Check if docker-compose is available
  if command -v docker-compose &> /dev/null; then
    # Start LLM services
    docker-compose -f docker/docker-compose.llm.yaml up -d
    
    echo -e "${GREEN}LLM services started successfully${NC}"
  else
    echo -e "${RED}Error: docker-compose not found${NC}"
    echo -e "${YELLOW}Please install docker-compose and try again${NC}"
    exit 1
  fi
}

# Check for GPU support
check_gpu_support() {
  echo -e "${BLUE}Checking for GPU support...${NC}"
  
  if command -v nvidia-smi &> /dev/null; then
    echo -e "${GREEN}NVIDIA GPU detected${NC}"
    # Check if nvidia-docker runtime is available
    if docker info | grep -q "nvidia"; then
      echo -e "${GREEN}NVIDIA Docker runtime available${NC}"
      export GPU_AVAILABLE=true
    else
      echo -e "${YELLOW}NVIDIA Docker runtime not found, falling back to CPU${NC}"
      export GPU_AVAILABLE=false
    fi
  else
    echo -e "${YELLOW}No NVIDIA GPU detected, running in CPU-only mode${NC}"
    export GPU_AVAILABLE=false
  fi
}

# Main execution
main() {
  echo -e "${BLUE}MCP-ZERO LLM Services${NC}"
  echo -e "${BLUE}====================${NC}"
  
  # Check offline mode
  check_offline_mode
  
  # Check GPU support
  check_gpu_support
  
  # Start LLM services
  start_llm_services
  
  echo -e "${GREEN}MCP-ZERO LLM services are now running${NC}"
  echo -e "${YELLOW}To stop services:${NC}"
  echo -e "docker-compose -f docker/docker-compose.llm.yaml down"
}

main "$@"
