#!/bin/bash
# Foxhunt HFT Trading System - TLI Client Launcher
# Connects to 3 standalone gRPC services as per TLI_PLAN.md

set -euo pipefail

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

echo -e "${BLUE}🖥️ Starting TLI (Terminal Line Interface) Client${NC}"
echo "=============================================="
echo "Connecting to: 3 Standalone gRPC Services"
echo ""

# Function to check if a service is available
check_service() {
    local service_name=$1
    local port=$2
    if nc -z localhost $port 2>/dev/null; then
        echo -e "${GREEN}✅ $service_name is available on port $port${NC}"
        return 0
    else
        echo -e "${RED}❌ $service_name is NOT available on port $port${NC}"
        return 1
    fi
}

# Check if services are running
echo -e "${YELLOW}🔍 Checking service availability...${NC}"
services_available=true

if ! check_service "Trading Service" 50051; then
    services_available=false
fi

if ! check_service "Backtesting Service" 50052; then
    services_available=false
fi

if ! check_service "ML Training Service" 50053; then
    services_available=false
fi

if [ "$services_available" = false ]; then
    echo ""
    echo -e "${YELLOW}⚠️ Some services are not running.${NC}"
    echo "Please start the system first:"
    echo "  ./start.sh"
    echo ""
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Set environment variables for TLI client
export RUST_LOG="info"
export TRADING_SERVICE_URL="http://localhost:50051"
export BACKTESTING_SERVICE_URL="http://localhost:50052"
export ML_TRAINING_SERVICE_URL="http://localhost:50053"

# Build TLI if needed
echo -e "${BLUE}🏗️ Building TLI client...${NC}"
if ! cargo build --release -p fxt; then
    echo -e "${RED}❌ Failed to build TLI client${NC}"
    exit 1
fi

echo -e "${GREEN}✅ TLI client built successfully${NC}"

# Display connection information
echo ""
echo -e "${GREEN}🎯 TLI Client Connection Configuration:${NC}"
echo "├── Trading Service:     $TRADING_SERVICE_URL"
echo "├── Backtesting Service: $BACKTESTING_SERVICE_URL"
echo "└── ML Training Service: $ML_TRAINING_SERVICE_URL"
echo ""
echo -e "${BLUE}📊 Starting TLI with 6 dashboards:${NC}"
echo "├── [T]rading Dashboard - Live positions, orders, executions"
echo "├── [R]isk Dashboard - VaR, limits, safety controls"
echo "├── [M]L Dashboard - Model predictions, signals"
echo "├── [P]erformance Dashboard - Returns, analytics"
echo "├── [B]acktesting Dashboard - Strategy testing"
echo "└── [C]onfiguration Dashboard - Settings management"
echo ""
echo -e "${GREEN}🚀 Launching TLI Client...${NC}"
echo ""

# Launch the TLI client
exec cargo run --release -p fxt