#!/bin/bash

# ==============================================================================
# B-connex — Autonomous Agent VM Launcher
# This script configures environment variables to route database, web server,
# and LLM completions from inside the VM back to the host machine.
# ==============================================================================

# Default settings (matches VirtualBox NAT config)
HOST_GATEWAY="10.0.2.2"
DEFAULT_ROLE="any"
DEFAULT_NAME="hotlot-vm"

# Parse CLI arguments
ROLE=$DEFAULT_ROLE
NAME=$DEFAULT_NAME
MODEL="qwen2.5:3b" # lightweight & fast under RAM limits

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --role) ROLE="$2"; shift ;;
        --as) NAME="$2"; shift ;;
        --model) MODEL="$2"; shift ;;
        --host-ip) HOST_GATEWAY="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

echo "=========================================================="
echo " 🤖 Antigravity VM Agent Launcher (Guest: hotlot) "
echo "=========================================================="
echo " Host Gateway: ${HOST_GATEWAY}"
echo " Agent ID    : ${NAME}"
echo " Claiming    : role '${ROLE}'"
echo " LLM Model   : ${MODEL}"
echo "=========================================================="
echo ""

# Inject database, application, and Ollama hosts pointing to the host machine
export DB_HOST="${HOST_GATEWAY}"
export DB_PORT="3306"
export DB_NAME="bconnex"
export DB_USER="root"
export DB_PASS="copilot2026"

export APP_URL="http://${HOST_GATEWAY}:8081"
export OLLAMA_HOST="http://${HOST_GATEWAY}:11434"

# Get script parent directory to resolve absolute path
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "Checking connectivity to Host Database (${DB_HOST}:${DB_PORT})..."
nc -zv -w 2 "${DB_HOST}" "${DB_PORT}" 2>&1
if [ $? -ne 0 ]; then
    echo "❌ Error: Cannot connect to Host database at ${DB_HOST}:${DB_PORT}."
    echo "   Please verify that MariaDB/MySQL is running on the host and allows remote connections."
    exit 1
fi
echo "✅ Database port is open!"
echo ""

echo "Checking connectivity to Host Ollama (${HOST_GATEWAY}:11434)..."
nc -zv -w 2 "${HOST_GATEWAY}" 11434 2>&1
if [ $? -ne 0 ]; then
    echo "❌ Error: Cannot connect to Host Ollama at http://${HOST_GATEWAY}:11434."
    echo "   Please make sure Ollama is running on your host machine and OLLAMA_HOST=0.0.0.0 environment variable is configured."
    exit 1
fi
echo "✅ Ollama is reachable!"
echo ""

export ROOM_LAYOUT="room"
case "${ROLE}" in
    pm)       ROOM_LANE="long-orchestrator"; ROOM_NAME="Long Memory Orchestrator"; ROOM_MODEL="deepseek-r1:70b"; ROOM_ROLE="pm" ;;
    backend)  ROOM_LANE="coding-assistant";   ROOM_NAME="Coding Assistant";       ROOM_MODEL="deepseek-coder-v2:16b"; ROOM_ROLE="backend" ;;
    frontend) ROOM_LANE="fast-executor";      ROOM_NAME="Fast Executor";          ROOM_MODEL="deepseek-r1:8b"; ROOM_ROLE="frontend" ;;
    qa)       ROOM_LANE="memory-steward";     ROOM_NAME="Memory Steward";         ROOM_MODEL="deepseek-coder-v2:16b"; ROOM_ROLE="qa" ;;
    *)        ROOM_LANE="memory-steward";     ROOM_NAME="Memory Steward";         ROOM_MODEL="deepseek-coder-v2:16b"; ROOM_ROLE="qa" ;;
esac
export ROOM_LANE ROOM_NAME ROOM_MODEL ROOM_ROLE
export ROOM_IDENTITY="${ROOM_LANE}"
export ROOM_GPU="CPU RAM"
export ROOM_CTX="16384"
if [ "${ROOM_LANE}" = "fast-executor" ]; then ROOM_GPU="GPU 99"; ROOM_CTX="8192"; fi
if [ "${ROOM_LANE}" = "long-orchestrator" ]; then ROOM_CTX="32768"; fi
export ROOM_NEXT="fast-executor"
if [ "${ROOM_LANE}" = "fast-executor" ]; then ROOM_NEXT="coding-assistant"; fi
if [ "${ROOM_LANE}" = "coding-assistant" ]; then ROOM_NEXT="memory-steward"; fi
if [ "${ROOM_LANE}" = "memory-steward" ]; then ROOM_NEXT="long-orchestrator"; fi
export ROOM_PROMPT="Work as one lane in the local four-agent room. Prefer handoff over overload."

echo "Starting autonomous agent loop..."
php "${PROJECT_ROOT}/scripts/agent-auton.php" --role "${ROOM_ROLE}" --as "${NAME}" --model "${ROOM_MODEL}"
