#!/bin/bash
# ============================================================
#  Orchera CARM Proxy AI - macOS Installer
#  Version: 1.3.0
#
#  Usage: curl -sL https://orchera.ca/downloads/install-mac.sh | bash
#     or: bash install-mac.sh
#
#  Installs: Node.js 22+, Ollama, 3 AI models, Orchera app
#  Location: ~/Applications/Orchera
# ============================================================

set -e

VERSION="1.3.0"
INSTALL_DIR="$HOME/Applications/Orchera"
MIRROR_DIR="$INSTALL_DIR/mirror_portal"
DATA_DIR="$INSTALL_DIR/mirror_portal/data"
LAUNCH_AGENT="$HOME/Library/LaunchAgents/ca.orchera.carm.plist"
PORT=3000

# Required AI models (downloaded via Ollama)
AI_MODELS=("phi4-mini" "llama3.2:1b" "qwen2.5-coder:1.5b")

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

step=0
total_steps=6

show_step() {
  step=$((step + 1))
  echo ""
  echo -e "${BLUE}[$step/$total_steps]${NC} ${BOLD}$1${NC}"
}

ok() { echo -e "  ${GREEN}OK${NC} $1"; }
warn() { echo -e "  ${YELLOW}!!${NC} $1"; }
fail() { echo -e "  ${RED}FAIL${NC} $1"; exit 1; }

# ============================================================
#  Banner
# ============================================================
echo ""
echo -e "${BOLD}============================================${NC}"
echo -e "${BOLD}  ORCHERA CARM Proxy AI - macOS Installer${NC}"
echo -e "${BOLD}  Version $VERSION${NC}"
echo -e "${BOLD}============================================${NC}"
echo ""
echo "  This will install Orchera to: $INSTALL_DIR"
echo "  Components: Node.js, Ollama AI engine, Orchera app"
echo "  Estimated time: 2-5 minutes (AI models download in background after install)"
echo ""
read -p "  Press Enter to continue (or Ctrl+C to cancel)... "

# ============================================================
#  Step 1: Check/Install Node.js 22+
# ============================================================
show_step "Checking Node.js..."

install_node() {
  if command -v brew &>/dev/null; then
    echo "  Installing Node.js 22 via Homebrew..."
    brew install node@22 2>/dev/null || brew upgrade node@22 2>/dev/null || true
    brew link --overwrite node@22 2>/dev/null || true
  else
    echo "  Homebrew not found. Installing Node.js directly..."
    local ARCH=$(uname -m)
    local NODE_URL=""
    if [ "$ARCH" = "arm64" ]; then
      NODE_URL="https://nodejs.org/dist/v22.15.0/node-v22.15.0-darwin-arm64.tar.gz"
    else
      NODE_URL="https://nodejs.org/dist/v22.15.0/node-v22.15.0-darwin-x64.tar.gz"
    fi
    local TMP_NODE="/tmp/orchera-node.tar.gz"
    curl -L --progress-bar "$NODE_URL" -o "$TMP_NODE"
    sudo mkdir -p /usr/local/lib/nodejs
    sudo tar -xzf "$TMP_NODE" -C /usr/local/lib/nodejs
    local NODE_DIR=$(ls -d /usr/local/lib/nodejs/node-v22* | head -1)
    echo "export PATH=$NODE_DIR/bin:\$PATH" >> "$HOME/.zprofile"
    export PATH="$NODE_DIR/bin:$PATH"
    rm -f "$TMP_NODE"
  fi
}

if command -v node &>/dev/null; then
  NODE_VER=$(node -v | sed 's/v//' | cut -d. -f1)
  if [ "$NODE_VER" -ge 22 ]; then
    ok "Node.js $(node -v) found"
  else
    warn "Node.js $(node -v) is too old (need v22+). Upgrading..."
    install_node
    ok "Node.js $(node -v) installed"
  fi
else
  warn "Node.js not found. Installing..."
  install_node
  ok "Node.js $(node -v) installed"
fi

# ============================================================
#  Step 2: Check/Install Ollama
# ============================================================
show_step "Checking Ollama AI engine..."

if command -v ollama &>/dev/null; then
  ok "Ollama found at $(which ollama)"
else
  warn "Ollama not found. Installing..."
  if command -v brew &>/dev/null; then
    brew install ollama 2>/dev/null
  else
    echo "  Downloading Ollama installer..."
    curl -fsSL https://ollama.com/install.sh | sh
  fi

  if command -v ollama &>/dev/null; then
    ok "Ollama installed"
  else
    fail "Could not install Ollama. Please install manually from https://ollama.com/download"
  fi
fi

# Start Ollama service if not running
if ! curl -s http://localhost:11434/api/version &>/dev/null; then
  echo "  Starting Ollama service..."
  ollama serve &>/dev/null &
  sleep 3
  if curl -s http://localhost:11434/api/version &>/dev/null; then
    ok "Ollama service started"
  else
    warn "Ollama service may need manual start. Continuing..."
  fi
else
  ok "Ollama service already running"
fi

# ============================================================
#  Step 3: Download AI models
# ============================================================
show_step "AI models will download on first launch..."

# Check which models are already available
MODELS_OK=0
MODELS_TOTAL=${#AI_MODELS[@]}
for model in "${AI_MODELS[@]}"; do
  if ollama list 2>/dev/null | grep -q "$model"; then
    MODELS_OK=$((MODELS_OK + 1))
    ok "$model already available"
  fi
done

if [ "$MODELS_OK" -eq "$MODELS_TOTAL" ]; then
  ok "All $MODELS_TOTAL AI models already installed"
else
  echo "  $MODELS_OK/$MODELS_TOTAL models available locally."
  echo "  Remaining models will download in the background when the app starts."
  echo "  You can start working immediately - invoice parsing works without AI."
  echo "  A progress bar in the app dashboard shows download status."
fi

# ============================================================
#  Step 4: Install Orchera app files
# ============================================================
show_step "Installing Orchera app files..."

mkdir -p "$INSTALL_DIR"
mkdir -p "$DATA_DIR"

# Check if this is an upgrade (preserve data)
if [ -f "$DATA_DIR/orchera.db" ]; then
  echo "  Existing installation detected - preserving your data..."
  UPGRADE=true
else
  UPGRADE=false
fi

# Download app bundle (or copy from local if running from repo)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_MIRROR="$SCRIPT_DIR/../../mirror_portal"

if [ -d "$REPO_MIRROR/server.js" ] || [ -f "$REPO_MIRROR/server.js" ]; then
  echo "  Copying from local repository..."
  rsync -a --exclude 'node_modules' --exclude 'data/orchera.db' \
    --exclude 'data/.trial_start' --exclude 'data/.trial_cache.json' \
    --exclude 'data/.license_token' --exclude 'data/.license_cache.json' \
    --exclude '.env' \
    "$REPO_MIRROR/" "$MIRROR_DIR/"
else
  echo "  Downloading Orchera v$VERSION..."
  local DOWNLOAD_URL="https://orchera.ca/downloads/orchera-v${VERSION}-mac.tar.gz"
  curl -L --progress-bar "$DOWNLOAD_URL" -o "/tmp/orchera-mac.tar.gz"
  tar -xzf "/tmp/orchera-mac.tar.gz" -C "$INSTALL_DIR"
  rm -f "/tmp/orchera-mac.tar.gz"
fi

# Create .env if it doesn't exist
if [ ! -f "$MIRROR_DIR/.env" ]; then
  echo "  Creating default configuration..."
  cat > "$MIRROR_DIR/.env" << 'ENVEOF'
PORT=3000
BYPASS_LICENSE=true
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=
NOTIFY_EMAIL=
ORCHERA_PUBLIC_KEY=-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEArE37HrRs/l1wXDoL2p1OvzgwcKtcuac8I4QrK8s9row=\n-----END PUBLIC KEY-----
ENVEOF
  ok "Configuration created"
fi

# Install npm dependencies
echo "  Installing dependencies (npm install)..."
cd "$MIRROR_DIR"
npm install --production --silent 2>/dev/null
ok "Dependencies installed"

# Create Inbound_Invoices folder
mkdir -p "$INSTALL_DIR/Inbound_Invoices"
mkdir -p "$INSTALL_DIR/logs"

# ============================================================
#  Step 5: Create start/stop scripts + auto-start
# ============================================================
show_step "Creating launch scripts..."

# Start script
cat > "$INSTALL_DIR/start-orchera.sh" << 'STARTEOF'
#!/bin/bash
# Start Orchera CARM Proxy AI
INSTALL_DIR="$HOME/Applications/Orchera"
cd "$INSTALL_DIR/mirror_portal"

# Start Ollama if not running
if ! curl -s http://localhost:11434/api/version &>/dev/null 2>&1; then
  echo "Starting Ollama AI engine..."
  ollama serve &>/dev/null &
  sleep 2
fi

# Start Node server
echo "Starting Orchera on http://localhost:3000..."
node server.js &
SERVER_PID=$!
echo $SERVER_PID > "$INSTALL_DIR/.orchera.pid"

# Wait for server to be ready
for i in {1..10}; do
  if curl -s http://localhost:3000/api/health &>/dev/null; then
    echo "Orchera is ready!"
    open "http://localhost:3000"
    break
  fi
  sleep 1
done

echo "Server PID: $SERVER_PID"
echo "To stop: ~/Applications/Orchera/stop-orchera.sh"
STARTEOF
chmod +x "$INSTALL_DIR/start-orchera.sh"

# Stop script
cat > "$INSTALL_DIR/stop-orchera.sh" << 'STOPEOF'
#!/bin/bash
# Stop Orchera CARM Proxy AI
INSTALL_DIR="$HOME/Applications/Orchera"
if [ -f "$INSTALL_DIR/.orchera.pid" ]; then
  PID=$(cat "$INSTALL_DIR/.orchera.pid")
  if kill -0 "$PID" 2>/dev/null; then
    kill "$PID"
    echo "Orchera server stopped (PID $PID)"
  else
    echo "Server not running"
  fi
  rm -f "$INSTALL_DIR/.orchera.pid"
else
  # Try to find and kill by port
  PID=$(lsof -ti:3000 2>/dev/null)
  if [ -n "$PID" ]; then
    kill "$PID"
    echo "Orchera server stopped (PID $PID)"
  else
    echo "Server not running"
  fi
fi
STOPEOF
chmod +x "$INSTALL_DIR/stop-orchera.sh"

# Uninstall script
SCRIPT_SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$SCRIPT_SELF_DIR/uninstall-orchera.sh" ]; then
  cp "$SCRIPT_SELF_DIR/uninstall-orchera.sh" "$INSTALL_DIR/uninstall-orchera.sh"
else
  # Create inline uninstaller if not bundled
  cat > "$INSTALL_DIR/uninstall-orchera.sh" << 'UNINSTEOF'
#!/bin/bash
echo "To uninstall Orchera, run:"
echo "  launchctl unload ~/Library/LaunchAgents/ca.orchera.carm.plist"
echo "  rm -rf ~/Applications/Orchera"
echo "  rm ~/Library/LaunchAgents/ca.orchera.carm.plist"
UNINSTEOF
fi
chmod +x "$INSTALL_DIR/uninstall-orchera.sh"

ok "start-orchera.sh, stop-orchera.sh, and uninstall-orchera.sh created"

# Create macOS Launch Agent (auto-start on login)
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$LAUNCH_AGENT" << PLISTEOF
<?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>ca.orchera.carm</string>
  <key>ProgramArguments</key>
  <array>
    <string>$INSTALL_DIR/start-orchera.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <false/>
  <key>WorkingDirectory</key>
  <string>$MIRROR_DIR</string>
  <key>StandardOutPath</key>
  <string>$INSTALL_DIR/logs/orchera-stdout.log</string>
  <key>StandardErrorPath</key>
  <string>$INSTALL_DIR/logs/orchera-stderr.log</string>
</dict>
</plist>
PLISTEOF

launchctl load "$LAUNCH_AGENT" 2>/dev/null || true
ok "Auto-start on login enabled"

# ============================================================
#  Step 6: Start and verify
# ============================================================
show_step "Starting Orchera..."

cd "$MIRROR_DIR"

# Check if port is available
if lsof -ti:$PORT &>/dev/null; then
  warn "Port $PORT is already in use. Stopping existing process..."
  kill $(lsof -ti:$PORT) 2>/dev/null || true
  sleep 2
fi

# Start the server
node server.js &>/dev/null &
SERVER_PID=$!
echo $SERVER_PID > "$INSTALL_DIR/.orchera.pid"

# Wait for server
echo "  Waiting for server to start..."
for i in {1..15}; do
  if curl -s http://localhost:$PORT/api/health &>/dev/null; then
    break
  fi
  sleep 1
done

if curl -s http://localhost:$PORT/api/health &>/dev/null; then
  ok "Server running on http://localhost:$PORT"
else
  warn "Server may still be starting. Try opening http://localhost:$PORT in a few seconds."
fi

# ============================================================
#  Done!
# ============================================================
echo ""
echo -e "${GREEN}${BOLD}============================================${NC}"
echo -e "${GREEN}${BOLD}  Installation Complete!${NC}"
echo -e "${GREEN}${BOLD}============================================${NC}"
echo ""
echo "  Orchera v$VERSION is installed at: $INSTALL_DIR"
echo "  AI models: $MODELS_OK/$MODELS_TOTAL ready"
echo ""
echo "  Commands:"
echo "    Start:     ~/Applications/Orchera/start-orchera.sh"
echo "    Stop:      ~/Applications/Orchera/stop-orchera.sh"
echo "    Uninstall: ~/Applications/Orchera/uninstall-orchera.sh"
echo ""
echo "  Auto-start: Orchera will start automatically on login."
echo "  Data:       ~/Applications/Orchera/mirror_portal/data/"
echo "  Invoices:   ~/Applications/Orchera/Inbound_Invoices/"
echo ""
if [ "$UPGRADE" = true ]; then
  echo -e "  ${YELLOW}Upgrade detected${NC} - your data has been preserved."
  echo ""
fi

# Open browser
echo "  Opening Orchera in your browser..."
open "http://localhost:$PORT"
echo ""
echo "  Happy declaring!"
echo ""
