#!/usr/bin/env bash

# Morphik Core one-liner installer + server launcher.
# Works on macOS (Apple Silicon or Intel) and Linux.
# Usage:  bash install_and_start.sh

set -euo pipefail

# Detect platform
OS=$(uname -s)
ARCH=$(uname -m)

# Check docker availability
if ! command -v docker >/dev/null 2>&1; then
  echo "❌ Docker is required (used to run a local Redis container). Install Docker Desktop or docker engine first." >&2
  exit 1
fi

printf "\n➡️  Detected OS: %s | Arch: %s\n" "$OS" "$ARCH"

# Ensure uv is installed globally (fallback to pipx if available)
if ! command -v uv >/dev/null 2>&1; then
  printf "\n🔧 Installing uv...\n"
  python3 -m pip install --user --upgrade uv || {
    echo "Failed to install uv – please make sure Python 3 & pip are available."; exit 1; }
fi

# Create virtual-env and sync project deps
printf "\n📦 Installing project dependencies with uv...\n"
uv sync

# shellcheck disable=SC1091
source .venv/bin/activate

# Ensure .env exists for python-dotenv (copy from example if missing)
if [[ ! -f .env && -f .env.example ]]; then
  printf "\n📄 Creating default .env from .env.example...\n"
  cp .env.example .env
fi

# Install ColPali engine (knowledge-graph generation)
printf "\n📦 Installing ColPali engine...\n"
uv pip install \
  colpali-engine@git+https://github.com/illuin-tech/colpali@80fb72c9b827ecdb5687a3a8197077d0d01791b3

# Extra build flags for Apple Silicon (Metal acceleration)
if [[ "$OS" == "Darwin" && "$ARCH" == "arm64" ]]; then
  printf "\n⚙️  Configuring Metal build flags for llama-cpp-python...\n"
  export CMAKE_ARGS="-DCMAKE_OSX_ARCHITECTURES=arm64 \
    -DCMAKE_APPLE_SILICON_PROCESSOR=arm64 \
    -DGGML_METAL=on"
fi

# Install llama-cpp with aggressive flags (rebuild to ensure proper arch back-end)
printf "\n📦 Installing llama-cpp-python...\n"
uv pip install --upgrade --verbose --force-reinstall --no-cache-dir \
  llama-cpp-python==0.3.5

printf "\n🚀 Starting Morphik server...\n\n"
uv run start_server.py
