name: Update Version Table in README
on:
  schedule:
    - cron: "0 */6 * * *"
  workflow_dispatch:
  workflow_run:
    workflows: ["Beta Pre-Release"]
    types:
      - completed
jobs:
  update-readme:
    if: |
      github.event_name != 'workflow_run' ||
      (
        github.event.workflow_run.conclusion == 'success' &&
        github.event.workflow_run.head_branch == 'beta'
      )
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          ref: beta
      - name: Fetch latest releases
        id: releases
        uses: actions/github-script@v7
        with:
          script: |
            const releases = await github.rest.repos.listReleases({
              owner: context.repo.owner,
              repo: context.repo.repo,
            });
            const stable = releases.data.find(r => !r.prerelease && !r.draft && r.tag_name.startsWith("v"));
            const beta = releases.data.find(r => r.prerelease && !r.draft && r.tag_name.startsWith("v"));
            
            // Check if beta is based on the same version as stable (e.g., 1.6.1 vs 1.6.1-beta)
            const isSameBaseVersion = stable && beta && 
              beta.tag_name.startsWith(stable.tag_name + '-');
            
            // Check if beta its version is lower than stable
            const isBetaOlder = stable && beta && beta.tag_name < stable.tag_name;
            
            const result = {
              stableTag: stable?.tag_name ?? "N/A",
              stableUrl: stable?.html_url ?? "#",
              betaTag: (isSameBaseVersion || isBetaOlder) ? "N/A" : (beta?.tag_name ?? "N/A"),
              betaUrl: (isSameBaseVersion || isBetaOlder) ? "#" : (beta?.html_url ?? "#")
            };
            console.log('Release info:', result);
            return result;
      - name: Set version info as env vars
        run: |
          echo 'STABLE_TAG=${{ fromJson(steps.releases.outputs.result).stableTag }}' >> $GITHUB_ENV
          echo 'STABLE_URL=${{ fromJson(steps.releases.outputs.result).stableUrl }}' >> $GITHUB_ENV
          echo 'BETA_TAG=${{ fromJson(steps.releases.outputs.result).betaTag }}' >> $GITHUB_ENV
          echo 'BETA_URL=${{ fromJson(steps.releases.outputs.result).betaUrl }}' >> $GITHUB_ENV
      - name: Generate version table markdown
        run: |
          cat <<EOF > version_table.md
          | Channel    | Version                                                             | Notes                        |
          |------------|---------------------------------------------------------------------|------------------------------|
          | **Stable** | [$STABLE_TAG]($STABLE_URL)                                        | Recommended for most users   |
          | **Beta**   | [$BETA_TAG]($BETA_URL)                                            | Includes new features        |
          EOF
      - name: Inject version table into README
        run: |
          if ! grep -q "<!-- versions:start -->" README.md; then
            echo "Warning: <!-- versions:start --> marker not found in README.md"
            exit 1
          fi
          
          # Create the updated README
          awk '
            BEGIN { in_block=0 }
            /<!-- versions:start -->/ {
              print;
              print "";
              # Read and print the version table
              system("cat version_table.md");
              print "";
              in_block=1;
              next
            }
            /<!-- versions:end -->/ { in_block=0; print; next }
            !in_block { print }
          ' README.md > README.tmp && mv README.tmp README.md
      - name: Commit and push if changed
        run: |
          git config --local user.name "github-actions[bot]"
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add README.md
          if git diff --cached --quiet; then
            echo "No changes to commit"
          else
            git commit -m "chore: update version table in README [skip ci]"
            git push
          fi
