#!/usr/bin/env bash
# ── @kaiban/sdk — publish to npm ──────────────────────────────────────────────
#
# Usage:
#   ./publish.sh          # full publish
#   ./publish.sh --dry    # dry run (no actual publish)
#
# Prerequisites:
#   npm login  (or set NPM_TOKEN env var for CI)

set -euo pipefail

PACKAGE_NAME="@kaiban/sdk"
DRY_RUN=false

# ── Parse args ────────────────────────────────────────────────────────────────
for arg in "$@"; do
  case $arg in
    --dry) DRY_RUN=true ;;
    *) echo "Unknown argument: $arg" && exit 1 ;;
  esac
done

# ── Colors ────────────────────────────────────────────────────────────────────
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log()  { echo -e "${GREEN}▶ $1${NC}"; }
warn() { echo -e "${YELLOW}⚠ $1${NC}"; }
fail() { echo -e "${RED}✗ $1${NC}" && exit 1; }

# ── cd to package root ────────────────────────────────────────────────────────
cd "$(dirname "$0")"

PACKAGE_VERSION=$(node -p "require('./package.json').version")
log "Publishing ${PACKAGE_NAME}@${PACKAGE_VERSION}"

# ── 1. Check npm auth ─────────────────────────────────────────────────────────
log "Checking npm authentication..."
if ! npm whoami &>/dev/null; then
  fail "Not logged in to npm. Run: npm login"
fi
NPM_USER=$(npm whoami)
log "Authenticated as: ${NPM_USER}"

# ── 2. Typecheck ──────────────────────────────────────────────────────────────
log "Running typecheck..."
npm run typecheck

# ── 3. Build ──────────────────────────────────────────────────────────────────
log "Building dist..."
npm run build

# ── 4. Verify dist ───────────────────────────────────────────────────────────
log "Verifying dist artifacts..."
for file in dist/index.js dist/index.cjs dist/index.d.ts dist/index.d.cts; do
  [ -f "$file" ] || fail "Missing artifact: $file"
done
log "All artifacts present."

# ── 5. Publish ────────────────────────────────────────────────────────────────
if [ "$DRY_RUN" = true ]; then
  warn "Dry run — skipping actual publish."
  npm publish --access public --dry-run
else
  log "Publishing to npm..."
  npm publish --access public
  log "✓ ${PACKAGE_NAME}@${PACKAGE_VERSION} published successfully."

  # ── 6. Deprecate legacy v1 ────────────────────────────────────────────────
  log "Deprecating legacy @kaiban/sdk@<2.0.0..."
  npm deprecate "@kaiban/sdk@<2.0.0" \
    "Upgrade to @kaiban/sdk@^2.0.0 — complete rewrite for Kaiban API v2. See CHANGELOG for migration details." \
    || warn "Could not deprecate legacy versions (may not exist on registry yet)."

  log "Done. 🎯"
fi
