#!/bin/bash
set -euo pipefail

# AgentInstaller - memU Bot Professional Installer
# High-performance 24/7 Proactive Memory Layer Setup
# https://agentinstaller.com/memubot

BOLD='\033[1m'
ACCENT='\033[38;2;99;102;241m' # Indigo for memU
SUCCESS='\033[38;2;34;197;94m'
WARN='\033[38;2;234;179;8m'
ERROR='\033[38;2;239;68;68m'
NC='\033[0m'

echo -e "${ACCENT}${BOLD}"
echo "╔════════════════════════════════════════════╗"
echo "║      memU Bot - Proactive Memory Setup     ║"
echo "║       Universal Intelligence Installer     ║"
echo "║          https://agentinstaller.com        ║"
╚════════════════════════════════════════════╝"
echo -e "${NC}"

# Detect OS
OS="unknown"
if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macos"
elif [[ "$OSTYPE" == "linux-gnu"* ]] || [[ -n "${WSL_DISTRO_NAME:-}" ]]; then
    OS="linux"
fi

echo -e "${SUCCESS}✓${NC} Environment: $OS detected"

# Check Python version (MemU prefers 3.13)
check_python() {
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
        # We check for >= 3.10 but inform that 3.13 is best
        MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
        MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)
        if [ "$MAJOR" -eq 3 ] && [ "$MINOR" -ge 10 ]; then
            echo -e "${SUCCESS}✓${NC} Python $PYTHON_VERSION confirmed"
            return 0
        fi
    fi
    echo -e "${WARN}→${NC} Python 3.10+ not found"
    return 1
}

# Check for uv
check_uv() {
    if command -v uv &> /dev/null; then
        echo -e "${SUCCESS}✓${NC} uv package manager confirmed"
        return 0
    fi
    return 1
}

setup_uv() {
    echo -e "${WARN}→${NC} Installing uv for high-speed dependency management..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    source $HOME/.cargo/env || true
}

if ! check_python; then
    echo -e "${ERROR}Error: Python 3.10 or higher is required.${NC}"
    exit 1
fi

if ! check_uv; then
    setup_uv
fi

# Clone and Setup
INSTALL_DIR="memu-bot"
echo -e "${WARN}→${NC} Initializing memU in ./${INSTALL_DIR}..."

if [ -d "$INSTALL_DIR" ]; then
    echo -e "${WARN}→${NC} Directory ${INSTALL_DIR} already exists. Updating..."
    cd "$INSTALL_DIR"
    git pull
else
    git clone https://github.com/NevaMind-AI/MemU.git "$INSTALL_DIR"
    cd "$INSTALL_DIR"
fi

echo -e "${WARN}→${NC} Installing dependencies utilizing uv sync..."
if command -v uv &> /dev/null; then
    uv sync
else
     echo -e "${WARN}→${NC} Falling back to standard pip install..."
     python3 -m venv venv
     source venv/bin/activate
     pip install -e .
fi

# Optional Postgres Check
if command -v docker &> /dev/null; then
    echo ""
    echo -e "${ACCENT}Recommended: PostgreSQL with pgvector${NC}"
    read -p "Would you like to start a local memU database via Docker? [y/N]: " run_db
    if [[ "$run_db" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        docker run -d \
          --name memu-postgres \
          -e POSTGRES_USER=postgres \
          -e POSTGRES_PASSWORD=postgres \
          -e POSTGRES_DB=memu \
          -p 5432:5432 \
          pgvector/pgvector:pg16
        echo -e "${SUCCESS}✓${NC} Database container started on port 5432"
    fi
fi

echo ""
echo -e "${SUCCESS}✓${NC} memU Bot installed successfully!"
echo -e "${SUCCESS}✓${NC} Proactive memory layer ready."
echo ""
echo -e "${ACCENT}${BOLD}Next Steps:${NC}"
echo "1. Set your OpenAI API Key:"
echo -e "   ${BOLD}export OPENAI_API_KEY='your-key-here'${NC}"
echo ""
echo "2. Run a proactive memory example:"
echo -e "   ${BOLD}cd examples/proactive && uv run proactive.py${NC}"
echo ""
echo "3. Deep Integration:"
echo "   Browse our guides at https://agentinstaller.com/memubot"
echo ""
echo -e "${SUCCESS}Join the Agentic Intelligence movement! 🧠${NC}"
