#!/usr/bin/env bash

# Start Infrastructure Tunnels for Brunix Assistance Engine
# Connects to the Devaron Cluster in Vultr Cloud

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
KUBECONFIG_PATH="$PROJECT_ROOT/$(grep KUBECONFIG_PATH "$PROJECT_ROOT/.env" | cut -d '=' -f2)"

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

echo -e "${GREEN}Starting Brunix Infrastructure Tunnels...${NC}"
echo ""

# Check if kubeconfig exists
if [ ! -f "$KUBECONFIG_PATH" ]; then
    echo "Error: Kubeconfig not found at $KUBECONFIG_PATH"
    exit 1
fi

# 1. AI Model Tunnel (Ollama)
echo -e "${YELLOW}[1/3]${NC} Starting Ollama Light Service tunnel (localhost:11434)..."
kubectl port-forward --address 0.0.0.0 svc/ollama-light-service 11434:11434 -n brunix --kubeconfig "$KUBECONFIG_PATH" &
OLLAMA_PID=$!

# 2. Knowledge Base Tunnel (Elasticsearch)
echo -e "${YELLOW}[2/3]${NC} Starting Elasticsearch Vector DB tunnel (localhost:9200)..."
kubectl port-forward --address 0.0.0.0 svc/brunix-vector-db 9200:9200 -n brunix --kubeconfig "$KUBECONFIG_PATH" &
ES_PID=$!

# 3. Observability DB Tunnel (PostgreSQL)
echo -e "${YELLOW}[3/3]${NC} Starting PostgreSQL tunnel (localhost:5432)..."
kubectl port-forward --address 0.0.0.0 svc/brunix-postgres 5432:5432 -n brunix --kubeconfig "$KUBECONFIG_PATH" &
PG_PID=$!

echo ""
echo -e "${GREEN}✓ All tunnels started successfully${NC}"
echo ""
echo "Process IDs:"
echo "  Ollama:        $OLLAMA_PID"
echo "  Elasticsearch: $ES_PID"
echo "  PostgreSQL:    $PG_PID"
echo ""
echo "To stop all tunnels, run:"
echo "  kill $OLLAMA_PID $ES_PID $PG_PID"
echo ""
