#!/bin/bash

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

echo -e "${BLUE}=========================================${NC}"
echo -e "${BLUE}  Payload CMS MCP Server Local Deployer  ${NC}"
echo -e "${BLUE}=========================================${NC}"
echo ""

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo -e "${RED}Docker is not installed. Please install Docker first.${NC}"
    echo "Visit https://docs.docker.com/get-docker/ for installation instructions."
    exit 1
fi

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo -e "${YELLOW}Docker Compose not found. Checking if it's available via Docker plugin...${NC}"
    if ! docker compose version &> /dev/null; then
        echo -e "${RED}Docker Compose is not available. Please install Docker Compose.${NC}"
        echo "Visit https://docs.docker.com/compose/install/ for installation instructions."
        exit 1
    else
        echo -e "${GREEN}Docker Compose plugin is available.${NC}"
        COMPOSE_CMD="docker compose"
    fi
else
    COMPOSE_CMD="docker-compose"
    echo -e "${GREEN}Docker Compose is installed.${NC}"
fi

# Check if .env file exists, if not create it from example
if [ ! -f .env ]; then
    echo -e "${YELLOW}No .env file found. Creating from .env.example...${NC}"
    cp .env.example .env
    echo -e "${GREEN}.env file created.${NC}"
else
    echo -e "${GREEN}.env file already exists.${NC}"
fi

# Start Redis and the MCP server using Docker Compose
echo -e "${BLUE}Starting Redis and MCP server...${NC}"
if [ "$COMPOSE_CMD" = "docker compose" ]; then
    docker compose up -d
else
    docker-compose up -d
fi

if [ $? -eq 0 ]; then
    echo -e "${GREEN}Services started successfully!${NC}"
    echo ""
    echo -e "${BLUE}=== Service Information ===${NC}"
    echo -e "MCP Server: ${GREEN}http://localhost:8080${NC}"
    echo -e "Health Check: ${GREEN}http://localhost:8080/health${NC}"
    echo -e "Redis: ${GREEN}localhost:6379${NC}"
    echo ""
    echo -e "${YELLOW}To view logs:${NC}"
    echo -e "  ${BLUE}$COMPOSE_CMD logs -f${NC}"
    echo ""
    echo -e "${YELLOW}To stop services:${NC}"
    echo -e "  ${BLUE}$COMPOSE_CMD down${NC}"
    echo ""
    echo -e "${GREEN}Payload CMS MCP Server is now running locally!${NC}"
else
    echo -e "${RED}Failed to start services. Please check the error messages above.${NC}"
    exit 1
fi 