#!/bin/bash
# API Test Runner Script

echo "========================================="
echo "  SkillDarbar API Test Suite Runner"
echo "========================================="
echo ""

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

# Check if Python venv exists
if [ ! -d "../../.venv" ]; then
    echo -e "${RED}Error: Virtual environment not found at ../../.venv${NC}"
    echo "Please create a virtual environment first"    
    exit 1
fi

# Check if API server is running
echo -e "${BLUE}Checking if API server is running on port 30015...${NC}"
if curl -s http://localhost:30015 > /dev/null 2>&1; then
    echo -e "${GREEN}✓ API server is running${NC}"
else
    echo -e "${YELLOW}⚠ API server is not running${NC}"
    echo -e "${YELLOW}Please start the API server first:${NC}"
    echo -e "  ${BLUE}source ../../.venv/bin/activate${NC}"
    echo -e "  ${BLUE}python app.py${NC}"
    echo
    read -p "Do you want to start the server now? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}Starting API server...${NC}"
        source ../../.venv/bin/activate
        cd ..
        python app.py &
        API_PID=$!
        echo -e "${GREEN}API server started with PID: $API_PID${NC}"
        echo -e "${BLUE}Waiting for server to be ready...${NC}"
        sleep 5
        cd tests
    else
        exit 1
    fi
fi

echo ""
echo -e "${BLUE}Running API tests...${NC}"
echo ""

# Activate virtual environment and run tests
source ../../.venv/bin/activate
python test_api.py

TEST_EXIT_CODE=$?

echo ""
if [ $TEST_EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}✓ All tests passed!${NC}"
else
    echo -e "${RED}✗ Some tests failed${NC}"
fi

# If we started the server, ask if we should stop it
if [ ! -z "$API_PID" ]; then
    echo ""
    read -p "Stop the API server? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        kill $API_PID
        echo -e "${YELLOW}API server stopped${NC}"
    fi
fi

exit $TEST_EXIT_CODE
