#!/bin/bash
# ═══════════════════════════════════════════════════════════════════════════════
#  ACE.Pro Neural Link Installer v2.0 - PRODUCTION
#  One-click installation for macOS
#  ───────────────────────────────────────────────────────────────────────────────
#  This script downloads and installs the REAL CleanForge engine.
#  Your files NEVER leave your machine - all processing is local.
# ═══════════════════════════════════════════════════════════════════════════════

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'
BRAND='\033[38;5;172m'

clear
echo ""
echo -e "${BRAND}╔═══════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BRAND}║                                                                   ║${NC}"
echo -e "${BRAND}║     █████╗  ██████╗███████╗   ██████╗ ██████╗  ██████╗           ║${NC}"
echo -e "${BRAND}║    ██╔══██╗██╔════╝██╔════╝   ██╔══██╗██╔══██╗██╔═══██╗          ║${NC}"
echo -e "${BRAND}║    ███████║██║     █████╗     ██████╔╝██████╔╝██║   ██║          ║${NC}"
echo -e "${BRAND}║    ██╔══██║██║     ██╔══╝     ██╔═══╝ ██╔══██╗██║   ██║          ║${NC}"
echo -e "${BRAND}║    ██║  ██║╚██████╗███████╗██╗██║     ██║  ██║╚██████╔╝          ║${NC}"
echo -e "${BRAND}║    ╚═╝  ╚═╝ ╚═════╝╚══════╝╚═╝╚═╝     ╚═╝  ╚═╝ ╚═════╝          ║${NC}"
echo -e "${BRAND}║                                                                   ║${NC}"
echo -e "${BRAND}║              N E U R A L   L I N K   I N S T A L L E R           ║${NC}"
echo -e "${BRAND}║                   v2.0 - Full Engine Edition                      ║${NC}"
echo -e "${BRAND}╚═══════════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Configuration
ACE_HOME="$HOME/.ace-pro"
ACE_ENGINE="$ACE_HOME/engine"
ACE_LOGS="$ACE_HOME/logs"
ACE_DATA="$ACE_HOME/data"
ACE_VENV="$ACE_HOME/venv"
LAUNCH_AGENT_PATH="$HOME/Library/LaunchAgents/com.ace-pro.neural-link.plist"
ENGINE_VERSION="2.0.0"
DOWNLOAD_URL="https://ace.sstiem.com/downloads/ace-pro-engine-${ENGINE_VERSION}.tar.gz"
PORT=17345
OLLAMA_MODEL="qwen2.5:1.5b"

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 1: System Diagnostic
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 1: SYSTEM DIAGNOSTIC${NC}"
echo ""

# Check macOS version
echo -n "  ◦ Checking macOS... "
MACOS_VERSION=$(sw_vers -productVersion)
echo -e "${GREEN}$MACOS_VERSION ✓${NC}"

# Check Python
echo -n "  ◦ Checking Python... "
if command -v python3 &> /dev/null; then
    PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
    PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
    PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)
    
    if [ "$PYTHON_MAJOR" -ge 3 ] && [ "$PYTHON_MINOR" -ge 9 ]; then
        echo -e "${GREEN}Python $PYTHON_VERSION ✓${NC}"
    else
        echo -e "${YELLOW}Python $PYTHON_VERSION (recommend 3.9+)${NC}"
    fi
else
    echo -e "${RED}NOT FOUND${NC}"
    echo ""
    echo -e "${YELLOW}  Python 3 is required. Installing via Homebrew...${NC}"
    if command -v brew &> /dev/null; then
        brew install python3
    else
        echo -e "${RED}  Please install Python 3.9+ from python.org${NC}"
        open "https://www.python.org/downloads/"
        exit 1
    fi
fi

# Check disk space
echo -n "  ◦ Checking disk space... "
AVAILABLE_SPACE=$(df -g "$HOME" | awk 'NR==2 {print $4}')
if [ "$AVAILABLE_SPACE" -ge 1 ]; then
    echo -e "${GREEN}${AVAILABLE_SPACE}GB available ✓${NC}"
else
    echo -e "${RED}Insufficient space (need 1GB)${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}  ✓ System diagnostic complete${NC}"
echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 2: Directory Structure
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 2: CREATING INFRASTRUCTURE${NC}"
echo ""

mkdir -p "$ACE_HOME"
mkdir -p "$ACE_ENGINE"
mkdir -p "$ACE_LOGS"
mkdir -p "$ACE_DATA"
mkdir -p "$HOME/Library/LaunchAgents"

echo -e "  ◦ Home:    ${WHITE}$ACE_HOME${NC}"
echo -e "  ◦ Engine:  ${WHITE}$ACE_ENGINE${NC}"
echo -e "  ◦ Logs:    ${WHITE}$ACE_LOGS${NC}"
echo -e "  ◦ Data:    ${WHITE}$ACE_DATA${NC}"
echo ""
echo -e "${GREEN}  ✓ Infrastructure ready${NC}"
echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 3: Download Engine
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 3: DOWNLOADING ENGINE${NC}"
echo ""

# Check if we need to download or update
CURRENT_VERSION=""
if [ -f "$ACE_ENGINE/VERSION" ]; then
    CURRENT_VERSION=$(cat "$ACE_ENGINE/VERSION")
fi

if [ "$CURRENT_VERSION" = "$ENGINE_VERSION" ]; then
    echo -e "  ◦ Engine v$ENGINE_VERSION already installed"
    echo -e "${GREEN}  ✓ Engine up to date${NC}"
else
    echo "  ◦ Downloading ACE.Pro Engine v$ENGINE_VERSION..."
    
    # Try to download from server, fall back to local copy if available
    TEMP_FILE="/tmp/ace-pro-engine-${ENGINE_VERSION}.tar.gz"
    
    if curl -fsSL "$DOWNLOAD_URL" -o "$TEMP_FILE" 2>/dev/null; then
        echo "  ◦ Extracting engine..."
        tar -xzf "$TEMP_FILE" -C "$ACE_HOME" --strip-components=1
        rm -f "$TEMP_FILE"
        echo -e "${GREEN}  ✓ Engine v$ENGINE_VERSION installed${NC}"
    else
        echo -e "${YELLOW}  ⚠ Could not download from server${NC}"
        echo "  ◦ Checking for bundled engine..."
        
        # Check if cleanforge is bundled with this installer (for offline install)
        SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
        if [ -d "$SCRIPT_DIR/../src/cleanforge" ]; then
            echo "  ◦ Using bundled engine from repository..."
            cp -r "$SCRIPT_DIR/../src/cleanforge" "$ACE_ENGINE/cleanforge"
            cp "$SCRIPT_DIR/../src/requirements.txt" "$ACE_ENGINE/requirements.txt"
            cp "$SCRIPT_DIR/../src/run_local.py" "$ACE_ENGINE/run_local.py"
            echo "$ENGINE_VERSION" > "$ACE_ENGINE/VERSION"
            echo -e "${GREEN}  ✓ Bundled engine installed${NC}"
        else
            echo -e "${RED}  ✗ No engine source available${NC}"
            echo "  Please download the engine manually from ace.sstiem.com"
            exit 1
        fi
    fi
fi

echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 4: Virtual Environment & Dependencies
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 4: INSTALLING DEPENDENCIES${NC}"
echo ""

if [ ! -d "$ACE_VENV" ]; then
    echo "  ◦ Creating virtual environment..."
    python3 -m venv "$ACE_VENV"
fi

echo "  ◦ Activating environment..."
source "$ACE_VENV/bin/activate"

echo "  ◦ Installing dependencies..."
pip install --upgrade pip --quiet
pip install -r "$ACE_ENGINE/requirements.txt" --quiet 2>/dev/null || pip install -r "$ACE_ENGINE/requirements.txt"

echo ""
echo -e "${GREEN}  ✓ Dependencies installed${NC}"
echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 5: Configure Auto-Start (LaunchAgent)
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 5: CONFIGURING AUTO-START${NC}"
echo ""

# Stop existing service if running
launchctl unload "$LAUNCH_AGENT_PATH" 2>/dev/null || true

# Create LaunchAgent plist
cat > "$LAUNCH_AGENT_PATH" << PLIST_EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.ace-pro.neural-link</string>
    <key>ProgramArguments</key>
    <array>
        <string>$ACE_VENV/bin/python</string>
        <string>$ACE_ENGINE/run_local.py</string>
    </array>
    <key>WorkingDirectory</key>
    <string>$ACE_ENGINE</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>ACE_LOCAL_MODE</key>
        <string>true</string>
        <key>PORT</key>
        <string>$PORT</string>
        <key>ACE_OLLAMA_MODEL</key>
        <string>$OLLAMA_MODEL</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>StandardOutPath</key>
    <string>$ACE_LOGS/engine.log</string>
    <key>StandardErrorPath</key>
    <string>$ACE_LOGS/engine-error.log</string>
    <key>ThrottleInterval</key>
    <integer>30</integer>
</dict>
</plist>
PLIST_EOF

# Load the service
launchctl load "$LAUNCH_AGENT_PATH"

echo -e "  ◦ LaunchAgent: ${WHITE}$LAUNCH_AGENT_PATH${NC}"
echo -e "  ◦ Auto-start:  ${GREEN}ENABLED${NC}"
echo ""
echo -e "${GREEN}  ✓ Auto-start configured${NC}"
echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 6: Create Management Tools
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 6: CREATING MANAGEMENT TOOLS${NC}"
echo ""

# Create start script
cat > "$ACE_HOME/start.command" << 'START_EOF'
#!/bin/bash
cd ~/.ace-pro
source venv/bin/activate
export ACE_LOCAL_MODE=true
export PORT=17345
export ACE_OLLAMA_MODEL="qwen2.5:1.5b"
python engine/run_local.py
START_EOF
chmod +x "$ACE_HOME/start.command"

# Create stop script
cat > "$ACE_HOME/stop.command" << 'STOP_EOF'
#!/bin/bash
launchctl unload ~/Library/LaunchAgents/com.ace-pro.neural-link.plist 2>/dev/null
pkill -f "run_local.py" 2>/dev/null
echo "ACE.Pro Neural Link stopped."
STOP_EOF
chmod +x "$ACE_HOME/stop.command"

# Create restart script
cat > "$ACE_HOME/restart.command" << 'RESTART_EOF'
#!/bin/bash
launchctl unload ~/Library/LaunchAgents/com.ace-pro.neural-link.plist 2>/dev/null
sleep 1
launchctl load ~/Library/LaunchAgents/com.ace-pro.neural-link.plist
echo "ACE.Pro Neural Link restarted."
RESTART_EOF
chmod +x "$ACE_HOME/restart.command"

# Create uninstall script
cat > "$ACE_HOME/uninstall.command" << 'UNINSTALL_EOF'
#!/bin/bash
echo "Uninstalling ACE.Pro Neural Link..."
launchctl unload ~/Library/LaunchAgents/com.ace-pro.neural-link.plist 2>/dev/null
rm -f ~/Library/LaunchAgents/com.ace-pro.neural-link.plist
rm -rf ~/.ace-pro
echo "ACE.Pro Neural Link has been uninstalled."
echo "Your files were never uploaded - they remain on your machine."
UNINSTALL_EOF
chmod +x "$ACE_HOME/uninstall.command"

# Create status script
cat > "$ACE_HOME/status.command" << 'STATUS_EOF'
#!/bin/bash
echo "ACE.Pro Neural Link Status"
echo "=========================="
if curl -s http://localhost:17345/health > /dev/null 2>&1; then
    echo "Status: ✓ RUNNING"
    echo ""
    curl -s http://localhost:17345/health | python3 -m json.tool 2>/dev/null || curl -s http://localhost:17345/health
else
    echo "Status: ✗ NOT RUNNING"
    echo ""
    echo "To start: ~/.ace-pro/start.command"
fi
STATUS_EOF
chmod +x "$ACE_HOME/status.command"

echo "  ◦ start.command     - Start manually"
echo "  ◦ stop.command      - Stop engine"
echo "  ◦ restart.command   - Restart engine"
echo "  ◦ status.command    - Check status"
echo "  ◦ uninstall.command - Remove ACE.Pro"
echo ""
echo -e "${GREEN}  ✓ Management tools created${NC}"
echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# PHASE 7: Verify Connection
# ═══════════════════════════════════════════════════════════════════════════════

echo -e "${CYAN}▸ PHASE 7: VERIFYING CONNECTION${NC}"
echo ""

# Wait for engine to start
echo "  ◦ Waiting for engine to start..."
sleep 3

# Check health
MAX_RETRIES=10
RETRY_COUNT=0
CONNECTED=false

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if curl -s "http://localhost:$PORT/health" > /dev/null 2>&1; then
        CONNECTED=true
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT + 1))
    echo "  ◦ Attempt $RETRY_COUNT/$MAX_RETRIES..."
    sleep 2
done

if [ "$CONNECTED" = true ]; then
    echo ""
    echo -e "${GREEN}  ✓ Neural Link is ONLINE at http://localhost:$PORT${NC}"
else
    echo ""
    echo -e "${YELLOW}  ⚠ Engine starting in background. Check status:${NC}"
    echo "     ~/.ace-pro/status.command"
fi

echo ""
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# COMPLETE
# ═══════════════════════════════════════════════════════════════════════════════

echo ""
echo -e "${BRAND}╔═══════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BRAND}║                                                                   ║${NC}"
echo -e "${BRAND}║          ✓ NEURAL LINK INSTALLATION COMPLETE                     ║${NC}"
echo -e "${BRAND}║                                                                   ║${NC}"
echo -e "${BRAND}╚═══════════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${WHITE}Your ACE.Pro Neural Link is now active.${NC}"
echo ""
echo -e "  ${CYAN}Engine:${NC}     $ACE_ENGINE"
echo -e "  ${CYAN}API:${NC}        http://localhost:$PORT"
echo -e "  ${CYAN}Dashboard:${NC}  https://ace.sstiem.com"
echo ""
echo -e "  ${GREEN}✓ Files processed locally - never uploaded${NC}"
echo -e "  ${GREEN}✓ Auto-starts on login${NC}"
echo -e "  ${GREEN}✓ Full PRO features enabled${NC}"
echo ""
echo -e "  ${YELLOW}Opening dashboard...${NC}"
echo ""

# Open dashboard
open "https://ace.sstiem.com/dashboard"

echo "  Press Enter to close this window..."
read
