name: Update Index

on:
  workflow_dispatch:

  schedule:
    - cron: '0 0 * * *'

jobs:
  discover:
    runs-on: ubuntu-latest

    permissions:
      contents: write

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

      - name: Install Bun
        uses: oven-sh/setup-bun@v2

      - name: Install Packages
        run: bun i

      - name: Run Index Job
        run: bun start
        working-directory: 'scripts/sync'
        env:
          GITHUB_TOKEN: ${{ secrets.INDEX_GH_TOKEN }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}

      - name: Commit and Push Changes
        run: |
          git config user.name "metorial[bot]"
          git config user.email "120314019+metorial@users.noreply.github.com"
          git add .
          if git diff --cached --quiet; then
            echo "No changes to commit."
          else
            git commit -m "Update index"
            git push
          fi

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: 'latest'
          files: |
            index.db
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
