name: Publish Package to npmjs

on:
  push:
    branches: [ main ]
    
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v3
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
      
      # Setup .npmrc file to publish to npm
      - uses: actions/setup-node@v3
        with:
          node-version: '16.x'
          registry-url: 'https://registry.npmjs.org'
      
      # Configure git user
      - name: Configure Git
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
      
      # Install dependencies
      - run: npm i
      
      # Bump version using current date format with build number (Beijing time)
      - name: Bump version
        run: |
          # Generate date in Beijing timezone and format properly
          YEAR=$(TZ='Asia/Shanghai' date +'%Y')
          MONTH=$(TZ='Asia/Shanghai' date +'%m' | sed 's/^0*//')
          DAY=$(TZ='Asia/Shanghai' date +'%d' | sed 's/^0*//')
          BASE_VERSION="$YEAR.$MONTH.$DAY"
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          
          # Get the latest build number from npm registry for today's date
          echo "Checking npm registry for existing versions of $BASE_VERSION..."
          
          # Also check if current local version represents today's date (handle malformed versions)
          CURRENT_BUILD=0
          if [[ "$CURRENT_VERSION" == *"-"* ]]; then
            # Handle malformed versions with dash (e.g., 2025.8.2-6.1)
            # Extract the number after the dash as the build number
            BUILD_PART=$(echo "$CURRENT_VERSION" | sed 's/.*-\([0-9]\+\)\..*/\1/')
            if [[ "$BUILD_PART" =~ ^[0-9]+$ ]]; then
              CURRENT_BUILD=$BUILD_PART
              echo "Detected malformed version $CURRENT_VERSION with build number $BUILD_PART"
            fi
          elif [[ "$CURRENT_VERSION" == "$BASE_VERSION"* ]]; then
            # Handle normal versions for today's date (both dot and dash formats)
            if [[ "$CURRENT_VERSION" == "$BASE_VERSION" ]]; then
              CURRENT_BUILD=0
            else
              # Handle both .X and -X formats
              BUILD_PART=$(echo "$CURRENT_VERSION" | sed "s|^$BASE_VERSION[-\.]||")
              if [[ "$BUILD_PART" =~ ^[0-9]+$ ]]; then
                CURRENT_BUILD=$BUILD_PART
              fi
            fi
          fi
          
          # Get all versions from npm and find the highest build number for today
          LATEST_BUILD=$CURRENT_BUILD
          if npm view shed-hs-static versions --json 2>/dev/null | grep -q "$BASE_VERSION"; then
            # Extract all versions that match today's date pattern (both dot and dash formats)
            VERSIONS=$(npm view shed-hs-static versions --json 2>/dev/null | grep -o "$BASE_VERSION\([-\.][0-9]\+\)\?" | sort -V)
            
            for version in $VERSIONS; do
              if [[ "$version" == "$BASE_VERSION" ]]; then
                BUILD=0
              else
                # Handle both .X and -X formats
                BUILD=$(echo "$version" | sed "s|^$BASE_VERSION[-\.]||")
                if [[ "$BUILD" =~ ^[0-9]+$ ]]; then
                  if [[ $BUILD -gt $LATEST_BUILD ]]; then
                    LATEST_BUILD=$BUILD
                  fi
                fi
              fi
            done
          fi
          
          # Set new version with incremented build number (using dash format)
          NEW_BUILD=$((LATEST_BUILD + 1))
          NEW_VERSION="$BASE_VERSION-$NEW_BUILD"
          
          echo "Current version: $CURRENT_VERSION"
          echo "New version: $NEW_VERSION"
          
          if [[ "$NEW_VERSION" != "$CURRENT_VERSION" ]]; then
            echo "Setting version to: $NEW_VERSION"
            
            # Update package.json version directly
            node -e "
              const fs = require('fs');
              const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
              pkg.version = '$NEW_VERSION';
              fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');
            "
            
            # Update README.md with new version (only replace specific version numbers, not 'latest')
            sed -i "s|shed-hs-static@[0-9]\{4\}\.[0-9]\{1,2\}\.[0-9]\{1,2\}[-\.][0-9]\+|shed-hs-static@$NEW_VERSION|g" README.md
            
            git add package.json README.md
            git commit -m "Bump version to $NEW_VERSION"
            git push
          else
            echo "Version $NEW_VERSION is already current, skipping version bump"
          fi
      
      # Publish to npm
      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
          NPM_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
