#!/usr/bin/env bash
set -euo pipefail

registry="${PUBLISH_REGISTRY:-https://gitea.bytelyst.com/api/packages/learning_ai_user/npm/}"
userconfig="${PUBLISH_NPMRC:-/tmp/publish.npmrc}"
package_filter="${PACKAGE_FILTER:-@bytelyst/errors}"
dry_run="${DRY_RUN:-false}"

case "$dry_run" in
  true|false) ;;
  *) echo "DRY_RUN must be 'true' or 'false'; got '$dry_run'" >&2; exit 1 ;;
esac

echo "Using package filter: $package_filter"
echo "Dry run mode: $dry_run"
echo "Publish registry: $registry"

mkdir -p /tmp/tarballs
: > /tmp/packages-to-publish.tsv

for pkg_json in packages/*/package.json; do
  name=$(node -p "require('./$pkg_json').name")
  version=$(node -p "require('./$pkg_json').version")
  dir=$(dirname "$pkg_json")

  case "$name" in
    @bytelyst/*) ;;
    *) continue ;;
  esac

  case "$package_filter" in
    '@bytelyst/*'|'') ;;
    "$name") ;;
    *) continue ;;
  esac

  if npm view "$name@$version" version --userconfig "$userconfig" --registry "$registry" >/dev/null 2>&1; then
    echo "SKIP already published: $name@$version"
  else
    echo "QUEUE publish: $name@$version ($dir)"
    printf '%s\t%s\t%s\n' "$name" "$version" "$dir" >> /tmp/packages-to-publish.tsv
  fi
done

echo "Queued packages:"
cat /tmp/packages-to-publish.tsv || true

if [ ! -s /tmp/packages-to-publish.tsv ]; then
  echo "No unpublished packages matched the filter; nothing to do."
  exit 0
fi

while IFS=$'\t' read -r name version dir; do
  echo "=== $name@$version ==="
  pnpm --filter "$name" run build

  if node -e "const s=require('./$dir/package.json').scripts||{}; process.exit(s.test ? 0 : 1)"; then
    pnpm --filter "$name" test
  else
    echo "SKIP test: $name has no package.json scripts.test"
  fi

  (cd "$dir" && pnpm pack --pack-destination /tmp/tarballs)

  if [ "$dry_run" = "true" ]; then
    echo "DRY RUN: would publish $name@$version"
  else
    cp "$userconfig" "$dir/.npmrc"
    trap "rm -f '$dir/.npmrc'" EXIT
    (cd "$dir" && pnpm publish --no-git-checks --registry "$registry")
    rm -f "$dir/.npmrc"
    trap - EXIT

    npm view "$name@$version" version dist.shasum dist.tarball --userconfig "$userconfig" --registry "$registry"

    consumer_name="consumer-${name//@/}-${version}"
    consumer_name="${consumer_name//\//-}"
    consumer_dir="/tmp/$consumer_name"
    rm -rf "$consumer_dir"
    mkdir -p "$consumer_dir"
    cp "$userconfig" "$consumer_dir/.npmrc"
    printf '{"name":"publish-consumer-verify","private":true,"type":"module","dependencies":{"%s":"%s"}}\n' "$name" "$version" > "$consumer_dir/package.json"
    (cd "$consumer_dir" && pnpm install --no-frozen-lockfile)
    (cd "$consumer_dir" && node --input-type=module -e "const m=await import('$name'); console.log(Object.keys(m).sort().join(','));")
  fi
done < /tmp/packages-to-publish.tsv
