#!/usr/bin/env bash
# Maxy Phase 0 — Pi Setup Script
# Run on a fresh Raspberry Pi 5 (16GB) with Raspberry Pi OS (64-bit)
#
# Usage: curl -fsSL https://raw.githubusercontent.com/aeon-neo/getmaxy/main/platform/scripts/setup.sh | bash
#    or: git clone git@github.com:aeon-neo/getmaxy.git && cd getmaxy && bash platform/scripts/setup.sh

set -euo pipefail

REPO_URL="https://github.com/aeon-neo/getmaxy.git"
INSTALL_DIR="$HOME/maxy"

echo "================================================================"
echo "  Maxy Phase 0 — Setup"
echo "  AI for Productive People"
echo "================================================================"
echo ""

# ------------------------------------------------------------------
# 1. System dependencies + hostname + Avahi (mDNS)
# ------------------------------------------------------------------
echo "[1/8] Updating system packages and configuring network..."
sudo apt-get update -qq
sudo apt-get install -y -qq curl git unzip avahi-daemon avahi-utils

# Set hostname to 'maxy' so device is reachable at maxy.local
CURRENT_HOSTNAME=$(hostname)
if [ "$CURRENT_HOSTNAME" != "maxy" ]; then
  echo "  Setting hostname to 'maxy' (was '$CURRENT_HOSTNAME')..."
  sudo hostnamectl set-hostname maxy
  # Update /etc/hosts
  sudo sed -i "s/127\.0\.1\.1.*$/127.0.1.1\tmaxy/" /etc/hosts
fi

# Create Avahi service file for LAN discovery
sudo tee /etc/avahi/services/maxy.service > /dev/null <<AVAHI
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
  <name replace-wildcards="yes">Maxy on %h</name>
  <service>
    <type>_http._tcp</type>
    <port>19200</port>
    <txt-record>role=maxy</txt-record>
    <txt-record>path=/</txt-record>
  </service>
</service-group>
AVAHI

# Ensure Avahi is running
sudo systemctl enable avahi-daemon
sudo systemctl restart avahi-daemon
echo "  Device reachable at http://maxy.local:19200"

# ------------------------------------------------------------------
# 2. Node.js 20+
# ------------------------------------------------------------------
if command -v node &>/dev/null && [[ "$(node -v | cut -d. -f1 | tr -d v)" -ge 20 ]]; then
  echo "[2/8] Node.js $(node -v) already installed."
else
  echo "[2/8] Installing Node.js 22..."
  curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
  sudo apt-get install -y -qq nodejs
fi

# ------------------------------------------------------------------
# 3. Neo4j Community Edition 5.x
# ------------------------------------------------------------------
if command -v neo4j &>/dev/null; then
  echo "[3/8] Neo4j already installed."
else
  echo "[3/8] Installing Neo4j Community Edition 5..."

  # Neo4j 5.x requires Java 17+
  if ! java -version 2>&1 | grep -q '"17\.\|"21\.\|"22\.\|"23\.'; then
    echo "  Installing OpenJDK 17..."
    sudo apt-get install -y -qq openjdk-17-jre-headless
  fi

  # Add Neo4j repository
  curl -fsSL https://debian.neo4j.com/neotechnology.gpg.key | sudo gpg --yes --dearmor -o /usr/share/keyrings/neo4j.gpg 2>/dev/null
  echo "deb [signed-by=/usr/share/keyrings/neo4j.gpg] https://debian.neo4j.com stable 5" | sudo tee /etc/apt/sources.list.d/neo4j.list
  sudo apt-get update -qq
  sudo apt-get install -y -qq neo4j

  # Configure Neo4j for local use
  sudo sed -i 's/#server.default_listen_address=0.0.0.0/server.default_listen_address=127.0.0.1/' /etc/neo4j/neo4j.conf

  # Generate a strong random password and store it
  NEO4J_GENERATED_PASSWORD=$(openssl rand -base64 32 | tr -d '/+=' | head -c 32)
  mkdir -p "$INSTALL_DIR/platform/config"
  echo "$NEO4J_GENERATED_PASSWORD" > "$INSTALL_DIR/platform/config/.neo4j-password"
  chmod 600 "$INSTALL_DIR/platform/config/.neo4j-password"
  sudo neo4j-admin dbms set-initial-password "$NEO4J_GENERATED_PASSWORD"

  # Start and enable
  sudo systemctl enable neo4j
  sudo systemctl start neo4j
  echo "  Neo4j started. Password stored in platform/config/.neo4j-password"
fi

# ------------------------------------------------------------------
# 4. Ollama (local embeddings)
# ------------------------------------------------------------------
if command -v ollama &>/dev/null; then
  echo "[4/8] Ollama already installed."
else
  echo "[4/8] Installing Ollama..."
  curl -fsSL https://ollama.ai/install.sh | sh
fi

# Pull the embedding model
echo "  Pulling nomic-embed-text model (~300MB)..."
ollama pull nomic-embed-text

# ------------------------------------------------------------------
# 5. Cloudflared (Cloudflare Tunnel)
# ------------------------------------------------------------------
if command -v cloudflared &>/dev/null; then
  echo "[5/8] Cloudflared already installed."
else
  echo "[5/8] Installing cloudflared..."
  curl -fsSL https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64.deb -o /tmp/cloudflared.deb
  sudo dpkg -i /tmp/cloudflared.deb
  rm /tmp/cloudflared.deb
fi

# ------------------------------------------------------------------
# 6. Clone or update Maxy
# ------------------------------------------------------------------
if [ -d "$INSTALL_DIR/.git" ]; then
  echo "[6/8] Updating Maxy..."
  cd "$INSTALL_DIR"
  git pull --ff-only
else
  echo "[6/8] Cloning Maxy..."
  git clone "$REPO_URL" "$INSTALL_DIR"
  cd "$INSTALL_DIR"
fi

# ------------------------------------------------------------------
# 7. Install dependencies and build
# ------------------------------------------------------------------
echo "[7/8] Installing dependencies and building..."

# Platform MCP servers
cd "$INSTALL_DIR/platform"
npm install --quiet
npm run build

# Web app
cd "$INSTALL_DIR/maxy"
npm install --quiet
npm run build

# ------------------------------------------------------------------
# 8. Create account and apply schema
# ------------------------------------------------------------------
cd "$INSTALL_DIR"
if [ ! -f "$INSTALL_DIR/.seeded" ]; then
  echo "[8/8] Creating account and applying schema..."
  bash platform/scripts/seed-neo4j.sh
  touch "$INSTALL_DIR/.seeded"
fi

# ------------------------------------------------------------------
# Done
# ------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  Maxy is installed."
echo ""
echo "  Open in your browser:"
echo "    http://maxy.local:19200"
echo ""
echo "  Everything from here happens through conversation."
echo "================================================================"
