name: Update DbIP-City-lite Database

on:
  schedule:
    # Run on 1st, 2nd, and 3rd of every month at 06:00 UTC (DB-IP updates on 1st)
    - cron: '0 6 1-3 * *'
    # Also run every Sunday as backup check
    - cron: '0 6 * * 0'
  workflow_dispatch:
    inputs:
      force_publish:
        description: 'Force publish to npm even if no changes'
        required: false
        default: 'false'
        type: boolean

jobs:
  update:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write  # Required for npm trusted publishing (OIDC)

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '24'  # Node 24 includes npm 11.5.1+ required for OIDC
          registry-url: 'https://registry.npmjs.org'

      - name: Download latest DbIP-City-lite database
        run: |
          echo "Downloading DbIP-City-lite database..."

          # Get current year and month
          YEAR_MONTH=$(date +%Y-%m)
          echo "Downloading database for: ${YEAR_MONTH}"

          # Download the database
          HTTP_CODE=$(curl -w "%{http_code}" -fsSL -o dbip-city-lite.mmdb.gz \
            "https://download.db-ip.com/free/dbip-city-lite-${YEAR_MONTH}.mmdb.gz")

          # If current month fails, try previous month (in case we're early in the month)
          if [ "$HTTP_CODE" != "200" ] || [ ! -s dbip-city-lite.mmdb.gz ]; then
            echo "Current month not available, trying previous month..."
            PREV_MONTH=$(date -d "last month" +%Y-%m 2>/dev/null || date -v-1m +%Y-%m)
            echo "Trying: ${PREV_MONTH}"

            curl -fsSL -o dbip-city-lite.mmdb.gz \
              "https://download.db-ip.com/free/dbip-city-lite-${PREV_MONTH}.mmdb.gz"
          fi

          # Verify download succeeded (file should be > 1MB)
          if [ ! -f dbip-city-lite.mmdb.gz ]; then
            echo "Download failed - file not found"
            exit 1
          fi

          FILE_SIZE=$(stat -c%s dbip-city-lite.mmdb.gz 2>/dev/null || stat -f%z dbip-city-lite.mmdb.gz)
          echo "Downloaded file size: ${FILE_SIZE} bytes"

          if [ "$FILE_SIZE" -lt 1000000 ]; then
            echo "Downloaded file too small (${FILE_SIZE} bytes), might be an error page"
            cat dbip-city-lite.mmdb.gz
            exit 1
          fi

          echo "Database downloaded successfully"
          ls -lh dbip-city-lite.mmdb.gz

      - name: Check for changes
        id: check_changes
        run: |
          FORCE="${{ inputs.force_publish }}"
          if [ "$FORCE" == "true" ]; then
            echo "Force publish requested"
            echo "changed=true" >> $GITHUB_OUTPUT
          elif git diff --quiet dbip-city-lite.mmdb.gz 2>/dev/null; then
            echo "No changes detected"
            echo "changed=false" >> $GITHUB_OUTPUT
          else
            echo "Changes detected"
            echo "changed=true" >> $GITHUB_OUTPUT
          fi

      - name: Update version and commit
        if: steps.check_changes.outputs.changed == 'true'
        run: |
          # Bump patch version
          npm version patch --no-git-tag-version

          # Get new version
          NEW_VERSION=$(node -p "require('./package.json').version")
          echo "New version: $NEW_VERSION"

          # Update README with current date
          CURRENT_DATE=$(date +%Y-%m-%d)
          sed -i "s/Last updated: .*/Last updated: ${CURRENT_DATE}/" README.md

          # Configure git
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'

          # Commit and push
          git add .
          git commit -m "Update DbIP-City-lite database to v${NEW_VERSION} - ${CURRENT_DATE}"
          git push

      - name: Publish to npm
        if: steps.check_changes.outputs.changed == 'true'
        run: npm publish --provenance --access public

      - name: Summary
        run: |
          if [ "${{ steps.check_changes.outputs.changed }}" == "true" ]; then
            echo "### Database Updated Successfully" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "- New version published to npm" >> $GITHUB_STEP_SUMMARY
            echo "- CDN will be updated automatically via jsDelivr" >> $GITHUB_STEP_SUMMARY
          else
            echo "### No Updates Required" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "The database is already up to date." >> $GITHUB_STEP_SUMMARY
          fi
