name: Publish draft release

on:
  workflow_dispatch:  # Manual trigger; can be automated later

permissions:
  contents: write
  pull-requests: write

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
      
      - name: Get latest draft release
        id: draft
        run: |
          draft_info=$(gh release list --limit 5 --json tagName,isDraft --jq '.[] | select(.isDraft==true) | .tagName' | head -n1)
          echo "tag_name=${draft_info}" >> $GITHUB_OUTPUT
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Validate draft version
        run: |
          if [ -z "${{ steps.draft.outputs.tag_name }}" ]; then
            echo "No draft release found!" >&2
            exit 1
          fi
          echo "Found draft version: ${{ steps.draft.outputs.tag_name }}"

      
      - name: Create branch and commit VERSION
        run: |
          branch="update-version-${{ steps.draft.outputs.tag_name }}"
          # Delete remote branch if exists
          git push origin --delete "$branch" || echo "No remote branch to delete"
          git fetch origin main
          git checkout -b "$branch" origin/main
          # Write VERSION file and timestamp to ensure a diff
          version="${{ steps.draft.outputs.tag_name }}"
          echo "$version" | sed 's/^v//' > VERSION
          git add VERSION
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git commit -m "chore: add VERSION $version" --allow-empty


      - name: Sync upstream JSONs
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail
          tmp_dir=$(mktemp -d)
          api_url="https://api.github.com/repos/community-scripts/ProxmoxVE/contents/frontend/public/json"
          # Fetch file list (no subfolders)
          curl -sSL -H "Authorization: token $GH_TOKEN" "$api_url" \
            | jq -r '.[] | select(.type=="file") | .name' > "$tmp_dir/files.txt"

          # Download each file
          while IFS= read -r name; do
            curl -sSL -H "Authorization: token $GH_TOKEN" \
              "https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/frontend/public/json/$name" \
              -o "$tmp_dir/$name"
          done < "$tmp_dir/files.txt"

          mkdir -p json
          rsync -a --delete "$tmp_dir/" json/

          # Stage and amend commit to include JSON updates (and VERSION)
          git add json VERSION
          if ! git diff --cached --quiet; then
            git commit --amend --no-edit
          fi


      - name: Push changes
        run: |
          git push --force-with-lease --set-upstream origin "update-version-${{ steps.draft.outputs.tag_name }}"

      
      - name: Create PR with GitHub CLI
        id: pr
        run: |
            pr_url=$(gh pr create \
            --base main \
            --head update-version-${{ steps.draft.outputs.tag_name }} \
            --title "chore: add VERSION ${{ steps.draft.outputs.tag_name }}" \
            --body "Adds VERSION file for release ${{ steps.draft.outputs.tag_name }}" \
            --label automated)
    
            pr_number=$(echo "$pr_url" | awk -F/ '{print $NF}')
            echo $pr_number
            echo "pr_number=$pr_number" >> $GITHUB_OUTPUT
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

     
#      - name: Approve pull request
#        env:
#          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
#        run: |
#          PR_NUMBER="${{ steps.pr.outputs.pr_number }}"
#          if [ -n "$PR_NUMBER" ]; then
#            gh pr review $PR_NUMBER --approve
#          fi

      - name: Merge PR
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git config --global user.name "github-actions-automege[bot]"
          git config --global user.email "github-actions-automege[bot]@users.noreply.github.com"
          PR_NUMBER="${{ steps.pr.outputs.pr_number }}"
          if [ -n "$PR_NUMBER" ]; then
            gh pr merge "$PR_NUMBER" --squash --admin
          fi        
      
      - name: Wait for PR merge
        uses: actions/github-script@v7
        with:
          script: |
            const prNum = parseInt("${{ steps.pr.outputs.pr_number }}")
            let merged = false
            const maxRetries = 20
            let tries = 0
            while(!merged && tries < maxRetries){
              const pr = await github.rest.pulls.get({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: prNum
              })
              merged = pr.data.merged
              if(!merged){
                tries++
                console.log("Waiting for PR to merge...")
                await new Promise(r => setTimeout(r, 5000))
              }
            }
            if(!merged) throw new Error("PR not merged in time")

      - name: Create tag
        run: |
          git tag "${{ steps.draft.outputs.tag_name }}"
          git push origin "${{ steps.draft.outputs.tag_name }}"

      - name: Publish draft release
        run: gh release edit "${{ steps.draft.outputs.tag_name }}" --draft=false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
