#!/usr/bin/env bash
# ModelAPI CLI installer — tested production builds from aimodelapi.ai/downloads
set -euo pipefail

VERSION="${AIMODELAPI_CLI_VERSION:-1.0.0}"
BASE_URL="${AIMODELAPI_INSTALL_BASE:-https://aimodelapi.ai/downloads}"

echo "ModelAPI CLI installer v${VERSION}"
echo "This installs @aimodelapi/cli for Hermes/OpenClaw memory tidy."
echo ""

if ! command -v node >/dev/null 2>&1; then
  echo "Error: Node.js 18+ is required. Install from https://nodejs.org/"
  exit 1
fi

NODE_MAJOR=$(node -p "process.versions.node.split('.')[0]")
if [ "$NODE_MAJOR" -lt 18 ]; then
  echo "Error: Node.js 18+ required (found $(node -v))"
  exit 1
fi

# Prefer tarball from downloads if manifest lists one for this platform
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
  x86_64) ARCH="x64" ;;
  arm64|aarch64) ARCH="arm64" ;;
esac

MANIFEST="${BASE_URL}/manifest.json"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

if curl -fsSL "$MANIFEST" -o "$TMP/manifest.json" 2>/dev/null; then
  ARTIFACT=$(node -e "
    const m=require('$TMP/manifest.json');
    const k='${OS}-${ARCH}';
    const a=m.cli?.artifacts?.[k];
    if(a) console.log(a.file);
  " 2>/dev/null || true)
  if [ -n "${ARTIFACT:-}" ]; then
    echo "Downloading verified artifact: $ARTIFACT"
    curl -fsSL "${BASE_URL}/${ARTIFACT}" -o "$TMP/pkg.tgz"
    EXPECTED=$(node -e "const m=require('$TMP/manifest.json');console.log(m.cli?.artifacts?.['${OS}-${ARCH}']?.sha256||'')")
    if [ -n "$EXPECTED" ]; then
      ACTUAL=$(shasum -a 256 "$TMP/pkg.tgz" | awk '{print $1}')
      if [ "$ACTUAL" != "$EXPECTED" ]; then
        echo "Error: checksum mismatch. Aborting install."
        exit 1
      fi
      echo "Checksum OK"
    fi
    npm install -g "$TMP/pkg.tgz"
    echo "Installed aimodelapi CLI from signed tarball."
    aimodelapi memory paths --profile hermes 2>/dev/null || true
    exit 0
  fi
fi

echo "No platform tarball in manifest — installing via npm pack fallback."
echo "Run from a git checkout: cd packages/cli && npm install && npm link"
echo ""
echo "Or set MODELAPI_API_KEY and use npx with local path after clone."
echo "See https://aimodelapi.ai/downloads for release artifacts."
