#!/usr/bin/env sh

# Vendor html-to-markdown-rs core crate if vendor directory is not populated.
#
# Two strategies:
#   1. Monorepo: if we're inside the html-to-markdown monorepo, vendor directly
#      from the local crates/ directory (fast, used by CI and local dev).
#   2. Download: fetch the source archive from GitHub for the matching version
#      tag and run the vendoring script against the extracted tree.
#      This is the path taken by r-universe and anyone installing from a
#      source tarball built outside the monorepo.

if [ ! -f "src/rust/vendor/html-to-markdown-rs/Cargo.toml" ]; then
  # Strategy 1: monorepo
  REPO_ROOT="$(cd ../.. 2>/dev/null && pwd)"
  VENDOR_SCRIPT="${REPO_ROOT}/scripts/ci/r/vendor-core-crate.py"

  if [ -f "${VENDOR_SCRIPT}" ] && [ -d "${REPO_ROOT}/crates/html-to-markdown" ]; then
    echo "* vendoring html-to-markdown-rs core crate from monorepo..."
    REPO_ROOT="${REPO_ROOT}" python3 "${VENDOR_SCRIPT}" || {
      echo "ERROR: vendoring from monorepo failed."
      exit 1
    }
  else
    # Strategy 2: download source from GitHub
    VERSION="$(grep '^Version:' DESCRIPTION | sed 's/Version:[[:space:]]*//')"
    GITHUB_URL="https://github.com/kreuzberg-dev/html-to-markdown/archive/refs/tags/v${VERSION}.tar.gz"

    echo "* monorepo not detected — downloading html-to-markdown v${VERSION} source..."

    WORK="$(mktemp -d)"
    cleanup() { rm -rf "${WORK}"; }
    trap cleanup EXIT

    TARBALL="${WORK}/html-to-markdown-${VERSION}.tar.gz"

    if command -v curl >/dev/null 2>&1; then
      curl -fsSL "${GITHUB_URL}" -o "${TARBALL}"
    elif command -v wget >/dev/null 2>&1; then
      wget -q "${GITHUB_URL}" -O "${TARBALL}"
    else
      echo "ERROR: neither curl nor wget found. Cannot download source."
      exit 1
    fi

    if [ ! -s "${TARBALL}" ]; then
      echo "ERROR: failed to download source from ${GITHUB_URL}"
      exit 1
    fi

    tar xzf "${TARBALL}" -C "${WORK}"
    EXTRACTED="${WORK}/html-to-markdown-${VERSION}"

    if [ ! -d "${EXTRACTED}/crates/html-to-markdown" ]; then
      echo "ERROR: downloaded source does not contain expected crate structure."
      exit 1
    fi

    echo "* running vendoring script against downloaded source..."
    REPO_ROOT="${EXTRACTED}" python3 "${EXTRACTED}/scripts/ci/r/vendor-core-crate.py" || {
      echo "ERROR: vendoring from downloaded source failed."
      exit 1
    }

    VENDOR_SRC="${EXTRACTED}/packages/r/src/rust/vendor/html-to-markdown-rs"
    if [ ! -d "${VENDOR_SRC}" ]; then
      echo "ERROR: vendor directory was not created by vendoring script."
      exit 1
    fi

    mkdir -p src/rust/vendor
    cp -R "${VENDOR_SRC}" src/rust/vendor/html-to-markdown-rs
    echo "* vendoring complete."
  fi
fi

: "${R_HOME=$(R RHOME)}"
"${R_HOME}/bin/Rscript" tools/config.R
