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

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
PACKAGES_DIR="$REPO_ROOT/packages"
TMP_DIR="${TMPDIR:-/tmp}/bytelyst-gitea-publish"
REGISTRY_URL="${GITEA_NPM_REGISTRY_URL:-http://${GITEA_NPM_HOST:-localhost}:3300/api/packages/learning_ai_user/npm/}"
AUTH_TARGET="${REGISTRY_URL#http://}"
AUTH_TARGET="${AUTH_TARGET#https://}"
TOKEN="${GITEA_NPM_TOKEN:-}"
PACKAGE_FILTER="${1:-}"

if [ -z "$TOKEN" ]; then
  echo "❌ GITEA_NPM_TOKEN is required"
  exit 1
fi

rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"

publish_package() {
  local pkg_dir="$1"
  local package_name
  local package_version
  package_name="$(node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); process.stdout.write(pkg.name);" "$pkg_dir/package.json")"
  package_version="$(node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); process.stdout.write(pkg.version);" "$pkg_dir/package.json")"
  local safe_name
  safe_name="${package_name//@/}"
  safe_name="${safe_name//\//-}"
  local work_dir="$TMP_DIR/$safe_name-$package_version"
  local packed_tgz
  local final_tgz

  rm -rf "$work_dir"
  mkdir -p "$work_dir"

  echo "📦 Packing $package_name@$package_version"
  (
    cd "$pkg_dir"
    pnpm pack --pack-destination "$work_dir" >/dev/null
  )

  packed_tgz="$(find "$work_dir" -maxdepth 1 -name '*.tgz' | head -1)"
  if [ -z "$packed_tgz" ]; then
    echo "❌ Failed to pack $package_name@$package_version"
    exit 1
  fi

  mkdir -p "$work_dir/unpacked"
  tar -xzf "$packed_tgz" -C "$work_dir/unpacked"
  (
    cd "$work_dir/unpacked/package"
    npm pack --pack-destination "$work_dir" >/dev/null
  )

  final_tgz="$(find "$work_dir" -maxdepth 1 -name '*.tgz' | sort | tail -1)"
  if [ -z "$final_tgz" ]; then
    echo "❌ Failed to repack $package_name@$package_version"
    exit 1
  fi

  echo "🚀 Publishing $package_name@$package_version to $REGISTRY_URL"
  if ! npm publish "$final_tgz" \
    --registry "$REGISTRY_URL" \
    --"//${AUTH_TARGET}:_authToken=$TOKEN"; then
    echo "⚠️  Publish failed for $package_name@$package_version (possibly already published)"
  fi
}

while IFS= read -r -d '' pkg_json; do
  pkg_dir="$(dirname "$pkg_json")"
  pkg_name="$(node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); process.stdout.write(pkg.name);" "$pkg_json")"
  if [ -n "$PACKAGE_FILTER" ] && [ "$pkg_name" != "$PACKAGE_FILTER" ]; then
    continue
  fi
  publish_package "$pkg_dir"
done < <(find "$PACKAGES_DIR" -mindepth 2 -maxdepth 2 -name package.json -print0 | sort -z)

echo "✅ Local Gitea package publish complete"
