#!/bin/bash
# Foxhunt HFT Trading System - Complete System Shutdown
# Stops 3 standalone services + databases as per TLI_PLAN.md architecture

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

echo -e "${RED}🛑 Stopping Foxhunt HFT Trading System${NC}"
echo "================================================="
echo "Shutting down: 3 Services + Docker Databases"

# Step 1: Stop services by PID files if they exist
echo -e "${BLUE}🔌 Stopping standalone services...${NC}"

if [ -f .trading-service.pid ]; then
    TRADING_PID=$(cat .trading-service.pid)
    echo "📈 Stopping Trading Service (PID: $TRADING_PID)"
    kill $TRADING_PID 2>/dev/null || true
    rm -f .trading-service.pid
fi

if [ -f .backtesting-service.pid ]; then
    BACKTEST_PID=$(cat .backtesting-service.pid)
    echo "🔄 Stopping Backtesting Service (PID: $BACKTEST_PID)"
    kill $BACKTEST_PID 2>/dev/null || true
    rm -f .backtesting-service.pid
fi

if [ -f .ml-training-service.pid ]; then
    ML_PID=$(cat .ml-training-service.pid)
    echo "🧠 Stopping ML Training Service (PID: $ML_PID)"
    kill $ML_PID 2>/dev/null || true
    rm -f .ml-training-service.pid
fi

# Step 2: Fallback - kill by process name
echo -e "${YELLOW}🧹 Cleaning up any remaining service processes...${NC}"
pkill -f "trading-service" || true
pkill -f "backtesting-service" || true
pkill -f "ml-training-service" || true

# Give processes time to shut down gracefully
sleep 2

# Step 3: Stop Docker databases
echo -e "${BLUE}🗄️  Stopping Docker databases...${NC}"

# Use docker compose (newer) or docker-compose (older)
DOCKER_COMPOSE_CMD="docker compose"
if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
    DOCKER_COMPOSE_CMD="docker-compose"
fi

if command -v docker >/dev/null 2>&1; then
    echo "Stopping databases with $DOCKER_COMPOSE_CMD..."
    $DOCKER_COMPOSE_CMD down

    # Optional: Remove volumes (uncomment to completely clean databases)
    # echo -e "${YELLOW}⚠️ Removing database volumes (data will be lost)...${NC}"
    # docker volume rm foxhunt_postgres_data foxhunt_influxdb_data foxhunt_redis_data 2>/dev/null || true
else
    echo -e "${YELLOW}⚠️ Docker not found, skipping database shutdown${NC}"
fi

# Step 4: Clean up any remaining ports
echo -e "${YELLOW}🔍 Checking for services still using ports...${NC}"
for port in 50051 50052 50053; do
    PID=$(lsof -ti :$port 2>/dev/null || true)
    if [ ! -z "$PID" ]; then
        echo "⚠️ Force killing process $PID on port $port"
        kill -9 $PID 2>/dev/null || true
    fi
done

echo -e "${GREEN}✅ All services and databases stopped${NC}"
echo ""
echo "System components stopped:"
echo "├── Trading Service (port 50051)"
echo "├── Backtesting Service (port 50052)"
echo "├── ML Training Service (port 50053)"
echo "└── Databases (PostgreSQL, InfluxDB, Redis)"
echo ""
echo -e "${GREEN}System shutdown complete${NC}"