#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
PUBLISH_URL="https://test.pypi.org/legacy/"
DRY_RUN=false

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --prod)
      PUBLISH_URL=""
      shift
      ;;
    --dry-run)
      DRY_RUN=true
      shift
      ;;
    *)
      echo "Unknown option: $1"
      echo "Usage: $0 [--prod] [--dry-run]"
      echo "  --prod: Publish to production PyPI (default: TestPyPI)"
      echo "  --dry-run: Build only, don't publish"
      exit 1
      ;;
  esac
done

# Get all tags sorted by version
echo -e "${YELLOW}Fetching all tags...${NC}"
TAGS=($(git tag --sort=version:refname))

echo -e "${GREEN}Found ${#TAGS[@]} tags to publish${NC}"
echo ""

# Save current branch/commit
CURRENT_REF=$(git rev-parse --abbrev-ref HEAD)
if [ "$CURRENT_REF" = "HEAD" ]; then
  CURRENT_REF=$(git rev-parse HEAD)
fi

# Track statistics
SUCCESS_COUNT=0
FAILED_COUNT=0
SKIPPED_COUNT=0
FAILED_TAGS=()

# Publish each tag
for tag in "${TAGS[@]}"; do
  echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${YELLOW}Processing $tag...${NC}"

  # Checkout tag
  if ! git checkout "$tag" 2>/dev/null; then
    echo -e "${RED}✗ Failed to checkout $tag${NC}"
    FAILED_TAGS+=("$tag (checkout failed)")
    ((FAILED_COUNT++))
    continue
  fi

  # Clean previous build artifacts
  rm -rf dist/

  # Build
  echo "Building $tag..."
  if ! uv build 2>&1 | grep -v "^Building"; then
    echo -e "${RED}✗ Build failed for $tag${NC}"
    FAILED_TAGS+=("$tag (build failed)")
    ((FAILED_COUNT++))
    continue
  fi

  # Publish or skip if dry-run
  if [ "$DRY_RUN" = true ]; then
    echo -e "${GREEN}✓ Built $tag (dry-run, skipping publish)${NC}"
    ((SKIPPED_COUNT++))
  else
    echo "Publishing $tag to ${PUBLISH_URL:-PyPI}..."

    if [ -z "$PUBLISH_URL" ]; then
      # Production PyPI
      if uv publish --quiet; then
        echo -e "${GREEN}✓ Published $tag to PyPI${NC}"
        ((SUCCESS_COUNT++))
      else
        echo -e "${RED}✗ Publish failed for $tag${NC}"
        FAILED_TAGS+=("$tag (publish failed)")
        ((FAILED_COUNT++))
      fi
    else
      # TestPyPI
      if uv publish --publish-url "$PUBLISH_URL" --quiet; then
        echo -e "${GREEN}✓ Published $tag to TestPyPI${NC}"
        ((SUCCESS_COUNT++))
      else
        echo -e "${RED}✗ Publish failed for $tag${NC}"
        FAILED_TAGS+=("$tag (publish failed)")
        ((FAILED_COUNT++))
      fi
    fi
  fi

  echo ""
done

# Return to original branch/commit
echo -e "${YELLOW}Returning to original branch...${NC}"
git checkout "$CURRENT_REF"

# Clean up
rm -rf dist/

# Summary
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}SUMMARY${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo "Total tags: ${#TAGS[@]}"
if [ "$DRY_RUN" = true ]; then
  echo -e "${GREEN}Built: $SKIPPED_COUNT${NC}"
else
  echo -e "${GREEN}Successfully published: $SUCCESS_COUNT${NC}"
fi
echo -e "${RED}Failed: $FAILED_COUNT${NC}"

if [ ${#FAILED_TAGS[@]} -gt 0 ]; then
  echo ""
  echo -e "${RED}Failed tags:${NC}"
  for failed in "${FAILED_TAGS[@]}"; do
    echo -e "  ${RED}✗${NC} $failed"
  done
fi

echo ""
if [ "$DRY_RUN" = false ] && [ "$SUCCESS_COUNT" -gt 0 ]; then
  if [ -z "$PUBLISH_URL" ]; then
    echo -e "${GREEN}Published versions available at: https://pypi.org/project/langrepl/${NC}"
  else
    echo -e "${GREEN}Published versions available at: https://test.pypi.org/project/langrepl/${NC}"
  fi
fi
