#!/usr/bin/env bash
# ==============================================================================
# PortSync & Workspace AI Agent Acceleration Suite - 1-Click Zero-Touch Setup
# Run this script on ANY new machine or fresh clone to fully enable:
# - In-RAM RAG BM25 Code & AST Indexing
# - Docker Redis Cache (0.99ms)
# - Git Pre-Push automated actions pruner & guidelines sync
# - MCP IDE tools registration
# ==============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORTFOLIO_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "🚀 [PortSync AI Suite] Starting autonomous 1-click environment bootstrap..."

PY_EXEC=""

# Check PATH for python3 or python
if command -v python3 &>/dev/null; then
    PY_EXEC="python3"
elif command -v python &>/dev/null; then
    PY_EXEC="python"
fi

# Check local standalone python in .agents/tools/python
LOCAL_STANDALONE="$PORTFOLIO_DIR/.agents/tools/python/bin/python3"
if [ -z "$PY_EXEC" ] && [ -x "$LOCAL_STANDALONE" ]; then
    PY_EXEC="$LOCAL_STANDALONE"
fi

if [ -z "$PY_EXEC" ]; then
    echo "⚠️  Neither Python 3 nor Node was detected on this system!"
    echo "🚀 [PortSync AI Suite] Starting autonomous zero-dependency bootstrap for Linux/macOS..."

    # Method 1: Package manager if root or sudo available
    if command -v apt-get &>/dev/null; then
        echo "   • Installing python3 via apt-get..."
        if [ "$(id -u)" -eq 0 ]; then
            apt-get update -qq && apt-get install -y -qq python3 python3-pip curl
        elif command -v sudo &>/dev/null; then
            sudo apt-get update -qq && sudo apt-get install -y -qq python3 python3-pip curl
        fi
    elif command -v apk &>/dev/null; then
        echo "   • Installing python3 via apk..."
        apk add --no-cache python3 py3-pip curl
    elif command -v brew &>/dev/null; then
        echo "   • Installing python3 via brew..."
        brew install python3
    elif command -v dnf &>/dev/null; then
        echo "   • Installing python3 via dnf..."
        dnf install -y python3
    fi

    # Check again after package manager
    if command -v python3 &>/dev/null; then
        PY_EXEC="python3"
    fi

    # Method 2: Astral uv standalone portable Python (Zero root/sudo needed, 100% portable)
    if [ -z "$PY_EXEC" ] && command -v curl &>/dev/null; then
        echo "   • Downloading standalone portable Python via astral uv (zero root required)..."
        export UV_INSTALL_DIR="$PORTFOLIO_DIR/.agents/tools/uv"
        mkdir -p "$UV_INSTALL_DIR"
        curl -LsSf https://astral.sh/uv/install.sh | env CARGO_HOME="$UV_INSTALL_DIR" sh
        
        UV_BIN="$HOME/.local/bin/uv"
        [ -x "$UV_INSTALL_DIR/bin/uv" ] && UV_BIN="$UV_INSTALL_DIR/bin/uv"

        if [ -x "$UV_BIN" ]; then
            echo "   • Installing portable Python 3.11 into .agents/tools/python..."
            "$UV_BIN" python install 3.11 --install-dir "$PORTFOLIO_DIR/.agents/tools/python"
            # Locate installed python binary
            INSTALLED_PY=$(find "$PORTFOLIO_DIR/.agents/tools/python" -name python3 -type f -perm -u=x | head -n 1)
            if [ -x "$INSTALLED_PY" ]; then
                PY_EXEC="$INSTALLED_PY"
                echo "   ✓ Portable Python ready: $($PY_EXEC --version)"
            fi
        fi
    fi
fi

if [ -z "$PY_EXEC" ]; then
    echo "❌ Error: Could not automatically bootstrap Python on this system."
    echo "   Please install Python 3 (https://www.python.org/downloads/) or run: sudo apt install python3"
    exit 1
fi

echo "  ✓ Python verified: $($PY_EXEC --version) [$PY_EXEC]"

# Check & Install Node.js if missing
if ! command -v node &>/dev/null; then
    echo "  📦 Node.js not detected in PATH. Attempting automatic installation..."
    if command -v apt-get &>/dev/null; then
        if [ "$(id -u)" -eq 0 ]; then
            curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y -qq nodejs
        elif command -v sudo &>/dev/null; then
            curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && sudo apt-get install -y -qq nodejs
        fi
    elif command -v brew &>/dev/null; then
        brew install node
    elif command -v apk &>/dev/null; then
        apk add --no-cache nodejs npm
    fi
fi
if command -v node &>/dev/null; then
    echo "  ✓ Node.js verified: $(node --version)"
fi

# 2. Check & Start Redis
if (exec 3<>/dev/tcp/127.0.0.1/6379) 2>/dev/null; then
    exec 3<&- && exec 3>&-
    echo "  ✓ Local Redis is active and reachable on port 6379."
elif command -v docker &>/dev/null; then
    if ! docker ps --format '{{.Names}}' | grep -q "redis"; then
        echo "  ⚡ Starting local Redis container on port 6379..."
        docker run -d --name portsync-redis -p 6379:6379 --restart unless-stopped redis:7-alpine 2>/dev/null || true
    else
        echo "  ✓ Local Redis container is already running on port 6379."
    fi
else
    echo "  ⚠️ Docker not found; In-RAM RAG will run in standalone SQLite memory mode (still < 2ms!)."
fi

# 3. Initialize & Build In-RAM RAG Index
echo "  🧠 Building In-RAM RAG index across all workspaces..."
"$PY_EXEC" "$SCRIPT_DIR/agent_ram_rag.py" index

# 4. Synchronize Architectural Guidelines
echo "  🔄 Synchronizing architectural contracts across all 4 workspaces..."
"$PY_EXEC" "$SCRIPT_DIR/sync_workspace_guidelines.py"

# 5. Ensure Git Hooks are Installed
PRE_PUSH_HOOK="$PORTFOLIO_DIR/.git/hooks/pre-push"
if [ -d "$PORTFOLIO_DIR/.git" ]; then
    mkdir -p "$PORTFOLIO_DIR/.git/hooks"
    cat << EOF > "$PRE_PUSH_HOOK"
#!/bin/sh
"$PY_EXEC" scripts/prune_github_actions.py portfolioEngine || true
"$PY_EXEC" scripts/sync_workspace_guidelines.py || true
EOF
    chmod +x "$PRE_PUSH_HOOK"
    echo "  ✓ Git pre-push hook installed."
fi

# 6. Check Local LM Studio Server
if curl -s http://127.0.0.1:1234/v1/models &>/dev/null; then
    echo "  ✓ LM Studio server detected on port 1234 (Dual-Model Active)."
else
    echo "  ℹ️  LM Studio not running on port 1234. (In-RAM RAG will run on native BM25 FTS5 until LM Studio starts)."
fi

echo "================================================================================"
echo "✅ 10X AI ACCELERATOR FULLY ARMED & READY!"
echo "   • Cockpit UI: http://localhost:3000/admin/agents"
echo "   • Query Tool: $PY_EXEC scripts/agent_ram_rag.py search <query>"
echo "   • Git Helper: $PY_EXEC scripts/agent_git_helper.py diff"
echo "================================================================================"
