name: Update Social Cache

on:
  schedule:
    - cron: '0 */2 * * *'  # Every 2 hours (incremental)
    - cron: '0 4 * * 0'    # Weekly full refresh (Sundays 4 AM UTC)
  workflow_dispatch:
    inputs:
      full_refresh:
        description: 'Run full refresh instead of incremental'
        required: false
        default: 'false'
        type: boolean

permissions:
  contents: write

jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.DASHBOARD_GITHUB_TOKEN }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
          cache-dependency-path: docs/package-lock.json

      - name: Install dependencies
        run: npm ci
        working-directory: docs

      - name: Determine if full refresh
        id: mode
        run: |
          # Full refresh on Sundays (cron) or if manually triggered with full_refresh=true
          if [[ "${{ github.event.schedule }}" == "0 4 * * 0" ]] || [[ "${{ inputs.full_refresh }}" == "true" ]]; then
            echo "args=--full" >> "$GITHUB_OUTPUT"
            echo "Running FULL refresh"
          else
            echo "args=" >> "$GITHUB_OUTPUT"
            echo "Running incremental update"
          fi

      - name: Update social cache
        run: npx tsx scripts/update-social-cache.ts ${{ steps.mode.outputs.args }}
        working-directory: docs
        env:
          GITHUB_TOKEN: ${{ secrets.DASHBOARD_GITHUB_TOKEN }}

      - name: Commit if changed
        run: |
          git diff --quiet docs/public/social-cache.json && echo "No changes" && exit 0
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add docs/public/social-cache.json
          git commit -m "chore: update social cache [skip ci]"
          git push
