#!/bin/bash

# lbm CLI Installer
# Installs the lbm memory CLI + its sidecar liblbug shared library from GitHub releases.
#
#   curl -fsSL https://install.ladybugmem.ai | bash
#
# Env overrides:
#   LBM_VERSION      release tag, e.g. v0.1.0 (default: latest release)
#   LBM_INSTALL_DIR  install directory (default: /usr/local/bin if writable, else $HOME/bin)
#   LBM_NO_SMOKE     set to 1 to skip the post-install smoke test
#   LBM_NO_SQLITE    set to 1 to skip placing rel_canon.sqlite in the cache dir
#                    (the binary self-provisions it on first run anyway)

set -e

# Keep in sync with REL_CANON_DB_VERSION in crates/lb-memory/src/rel_canon.rs
# and REL_CANON_DB_VERSION in .github/workflows/release.yml.
REL_CANON_DB_VERSION="2"

REPO="Ladybug-Memory/ladybug-memory-rs"

echo "
🧠 Welcome to lbm Installer! 🧠

Installing the LadybugDB-backed agent memory CLI... 🚀
"

# Detect OS
os=$(uname -s)
case $os in
    Linux) os="linux" ;;
    Darwin) os="macos" ;;
    MINGW*|MSYS*|CYGWIN*) os="windows" ;;
    *) echo "❌ Unsupported OS: $os"; exit 1 ;;
esac

# Detect Architecture
arch=$(uname -m)
case $arch in
    x86_64|amd64) arch="x86_64" ;;
    aarch64|arm64) arch="aarch64" ;;
    *) echo "❌ Unsupported architecture: $arch"; exit 1 ;;
esac

# Map to release target triple + archive type
if [ "$os" = "macos" ]; then
    target="${arch}-apple-darwin"
    ext="tar.gz"
elif [ "$os" = "windows" ]; then
    if [ "$arch" != "x86_64" ]; then
        echo "❌ Windows builds are only published for x86_64"
        exit 1
    fi
    target="x86_64-pc-windows-msvc"
    ext="zip"
else
    target="${arch}-unknown-linux-gnu"
    ext="tar.gz"
fi

echo "🔍 Detected OS: $os, Architecture: $arch (target: $target)"

# Resolve version (latest release unless overridden)
if [ -z "$LBM_VERSION" ]; then
    echo "🔍 Resolving latest release..."
    if command -v curl >/dev/null 2>&1; then
        final_url=$(curl -fsSIL -o /dev/null -w '%{url_effective}' "https://github.com/${REPO}/releases/latest" 2>/dev/null || true)
        LBM_VERSION="${final_url##*/}"
    fi
    if [ -z "$LBM_VERSION" ] || [ "$LBM_VERSION" = "latest" ]; then
        if command -v curl >/dev/null 2>&1; then
            LBM_VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null | grep '"tag_name"' | cut -d'"' -f4 || true)
        elif command -v wget >/dev/null 2>&1; then
            LBM_VERSION=$(wget -qO- "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null | grep '"tag_name"' | cut -d'"' -f4 || true)
        fi
    fi
    if [ -z "$LBM_VERSION" ]; then
        echo "❌ Could not resolve the latest release. Set LBM_VERSION explicitly, e.g.:"
        echo "   curl -fsSL https://install.ladybugmem.ai | LBM_VERSION=v0.1.0 bash"
        exit 1
    fi
fi
# Normalize: allow "0.1.0" or "v0.1.0"
case $LBM_VERSION in
    v*) ;;
    *) LBM_VERSION="v$LBM_VERSION" ;;
esac

asset="lbm-${LBM_VERSION}-${target}.${ext}"
echo "📦 Installing $asset ($LBM_VERSION)"

# Create temp directory
temp_dir=$(mktemp -d)
cd "$temp_dir"

# Download the asset (+ checksum)
download_url="https://github.com/${REPO}/releases/download/${LBM_VERSION}/${asset}"
echo "⬇️  Downloading from: $download_url"

if command -v curl >/dev/null 2>&1; then
    curl -fSL -o "$asset" "$download_url"
elif command -v wget >/dev/null 2>&1; then
    wget -O "$asset" "$download_url"
else
    echo "❌ Neither curl nor wget found. Please install one of them."
    exit 1
fi

# Best-effort checksum verification (published alongside every bundle)
if command -v curl >/dev/null 2>&1; then
    if curl -fSL -o "${asset}.sha256" "${download_url}.sha256" 2>/dev/null; then
        if command -v sha256sum >/dev/null 2>&1; then
            sha256sum -c "${asset}.sha256" && echo "✅ Checksum OK"
        elif command -v shasum >/dev/null 2>&1; then
            shasum -a 256 -c "${asset}.sha256" && echo "✅ Checksum OK"
        else
            echo "⚠️  No sha256sum/shasum available — skipping checksum verification"
        fi
    else
        echo "⚠️  No checksum file published for $asset — skipping verification"
    fi
fi

# Extract
echo "📂 Extracting $asset..."
if [ "$ext" = "tar.gz" ]; then
    tar -xzf "$asset"
elif [ "$ext" = "zip" ]; then
    if command -v unzip >/dev/null 2>&1; then
        unzip -q "$asset"
    else
        echo "❌ unzip not found. Please install unzip."
        exit 1
    fi
fi

bundle_dir="lbm-${LBM_VERSION}-${target}"
if [ ! -d "$bundle_dir" ]; then
    echo "❌ Expected bundle directory $bundle_dir not found after extraction"
    ls -la
    exit 1
fi

# Install location: binary + shared lib MUST live in the same directory
# (rpath is @loader_path / $ORIGIN; Windows resolves DLLs beside the exe).
if [ -n "$LBM_INSTALL_DIR" ]; then
    install_dir="$LBM_INSTALL_DIR"
elif [ "$os" = "windows" ]; then
    install_dir="$HOME/bin"
else
    if mkdir -p /usr/local/bin 2>/dev/null && [ -w /usr/local/bin ]; then
        install_dir="/usr/local/bin"
    else
        install_dir="$HOME/bin"
    fi
fi
mkdir -p "$install_dir"

binary_name="lbm"
if [ "$os" = "windows" ]; then
    binary_name="lbm.exe"
fi
if [ ! -f "$bundle_dir/$binary_name" ]; then
    echo "❌ Binary $binary_name not found in bundle"
    ls -la "$bundle_dir"
    exit 1
fi

echo "🚚 Installing to $install_dir/"
cp "$bundle_dir/$binary_name" "$install_dir/"
if [ "$os" = "windows" ]; then
    # Runtime needs the DLL(s) beside the exe (.lib import libs stay behind).
    cp "$bundle_dir"/*.dll "$install_dir/" 2>/dev/null || true
elif [ "$os" = "macos" ]; then
    cp -P "$bundle_dir"/liblbug*.dylib "$install_dir/"
else
    cp -P "$bundle_dir"/liblbug.so* "$install_dir/"
fi
if [ "$os" != "windows" ]; then
    chmod +x "$install_dir/$binary_name"
fi

# Place rel_canon.sqlite where the binary looks for it:
# $HOME/.cache/ladybug-memory/rel_canon-v<REL_CANON_DB_VERSION>.sqlite
# (override with LB_MEMORY_REL_CANON_DB). The binary also embeds this DB
# and self-heals a stale spill, so this copy is belt-and-braces for
# air-gap setups — it must never block the install.
if [ "${LBM_NO_SQLITE:-0}" != "1" ] && [ -f "$bundle_dir/rel_canon.sqlite" ]; then
    cache_dir="$HOME/.cache/ladybug-memory"
    if mkdir -p "$cache_dir" 2>/dev/null; then
        bundled="$bundle_dir/rel_canon.sqlite"
        dest="$cache_dir/rel_canon-v${REL_CANON_DB_VERSION}.sqlite"
        if [ ! -f "$dest" ] || ! cmp -s "$bundled" "$dest"; then
            cp "$bundled" "$dest" 2>/dev/null && echo "📖 Placed rel_canon.sqlite in $dest" || echo "⚠️  Could not write $dest (first run will provision it)"
        else
            echo "📖 rel_canon.sqlite already current in $dest"
        fi
    else
        echo "⚠️  Could not create $cache_dir (first run will provision it)"
    fi
fi

# Smoke test: proves the binary finds its sidecar shared library.
if [ "${LBM_NO_SMOKE:-0}" != "1" ]; then
    echo "🔬 Smoke-testing the install..."
    "$install_dir/$binary_name" --version
    "$install_dir/$binary_name" --db "$temp_dir/smoke.lbdb" status >/dev/null
    echo "✅ Smoke test passed"
fi

# Cleanup
cd /
rm -rf "$temp_dir"

# PATH hint
case ":$PATH:" in
    *":$install_dir:"*) path_note="($install_dir is already on your PATH)" ;;
    *) path_note="— add it to your PATH: export PATH=\"$install_dir:\$PATH\"" ;;
esac

echo "
✅ Installation complete! 🎉

🧠 lbm $LBM_VERSION installed to $install_dir/ $path_note
   (keep the lbm binary and the liblbug library in the SAME directory)

Next steps:
  lbm fetch-model   # one-time: GLiNER snapshot (~780 MB) + ONNX Runtime lib (~35 MB)
  lbm status        # model: ready, database counts

Data lives at ~/.pi/agent/lb-memory/memory.lbdb by default
(override with --db / LB_MEMORY_DB). Graph (*.lbdb) and intake
(*.intake.sqlite) files are created on first use — never shipped.

Air-gap: point LB_MEMORY_REL_CANON_DB at a rel_canon.sqlite copy.
Windows: run this installer from Git Bash (or WSL).
"
