#!/bin/bash
# Cortex Agent Node — Seamless Runner
set -e

# Ensure we are in the script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
cd "$SCRIPT_DIR" || { echo "❌ Error: Could not change directory to $SCRIPT_DIR"; exit 1; }

echo "🚀 Starting Cortex Agent Node..."

# 1. Future Binary Check
if [ -f "./agent-node" ]; then
    echo "[*] Binary executable detected. Launching..."
    chmod +x ./agent-node
    ./agent-node
    exit $?
fi

# 2. Source Code Fallback
if [ -d "./src/agent_node" ]; then
    echo "[*] Source code detected. Setting up Python environment..."
    if ! command -v python3 &> /dev/null; then
        echo "❌ Error: python3 not found. Please install Python 3.10+."
        exit 1
    fi

    VENV=".venv"
    if [ ! -d "$VENV" ]; then
        echo "[*] Creating virtual environment..."
        python3 -m venv "$VENV"
    fi
    source "$VENV/bin/activate"

    if [ -f "requirements.txt" ]; then
        echo "[*] Syncing dependencies..."
        pip install --upgrade pip --quiet
        pip install -r requirements.txt --quiet
    fi

    echo "✅ Environment ready. Booting node..."
    echo "💡 Tip: To install as a persistent background service (survives reboots), run: python3 bootstrap_installer.py --daemon"
    python3 src/agent_node/main.py
else
    echo "❌ Error: No executable ('agent-node') or source code ('src/agent_node/') found in this bundle."
    exit 1
fi
