## Updates demo site (https://github.com/zetxek/adritian-demo)
## taken from https://stackoverflow.com/a/68213855/570087

name: Preview demo site

permissions:
  contents: read
  id-token: write
  pages: write
  pull-requests: write
  checks: write
  statuses: write
  actions: write
## This will open a PR which will open a vercel preview URL in the demo site

on:
  pull_request:
    branches: [main]
  workflow_dispatch:

jobs:
  label-dependabot:
    runs-on: ubuntu-latest
    if: github.actor == 'dependabot[bot]'
    steps:
      - name: Add safe-to-test label to Dependabot PRs
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            try {
              // First check if the label exists
              await github.rest.issues.getLabel({
                owner: context.repo.owner,
                repo: context.repo.repo,
                name: 'safe-to-test'
              });
              
              // If it exists, add it to the PR
              await github.rest.issues.addLabels({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                labels: ['safe-to-test']
              });
              console.log('Added safe-to-test label to PR');
            } catch (error) {
              // If getting the label failed, the PR workflow can't add it
              // Let's just modify our workflow to handle this differently
              console.log('Could not add safe-to-test label: ' + error.message);
              console.log('Will handle Dependabot PRs directly in check-conditions job');
            }

  check-dependabot:
    runs-on: ubuntu-latest
    outputs:
      should-run: ${{ steps.check-conditions.outputs.should-run }}
    steps:
      - id: check-conditions
        run: |
          # Check if PR has safe-to-test label
          if [[ "${{ contains(github.event.pull_request.labels.*.name, 'safe-to-test') }}" == "true" ]]; then
            echo "should-run=true" >> $GITHUB_OUTPUT
            echo "PR has safe-to-test label, allowing workflow to run"
            exit 0
          fi
          
          # Always allow Dependabot PRs to run
          if [[ "${{ github.actor }}" == "dependabot[bot]" ]]; then
            echo "should-run=true" >> $GITHUB_OUTPUT
            echo "PR is from Dependabot, automatically allowing workflow to run"
            exit 0
          fi
          
          # For other contributors
          echo "should-run=true" >> $GITHUB_OUTPUT
          echo "PR is from a trusted contributor, allowing workflow to run"

  update-demo:
    needs: check-dependabot
    if: needs.check-dependabot.outputs.should-run == 'true'
    env:
      SOURCE_BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
      PR_NUMBER: ${{ github.event.number }}
      HUGO_VERSION: ${{ vars.HUGO_VERSION || '0.147.2' }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source repository
        uses: actions/checkout@v4
        with: 
          repository: zetxek/adritian-free-hugo-theme
          ref: ${{ github.head_ref || github.ref_name }}
          token: ${{ secrets.PRIVATE_TOKEN_GITHUB }}
          path: source-repo
          
      - name: Checkout demo repository  
        uses: actions/checkout@v4
        with: 
          repository: zetxek/adritian-demo
          token: ${{ secrets.PRIVATE_TOKEN_GITHUB }}
          path: demo-repo 
     
      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: ${{ env.HUGO_VERSION }}
          extended: true
     
      - name: Send pull-request
        shell: bash        
        run: |
          SOURCE_REPOSITORY="zetxek/adritian-free-hugo-theme"
          LATEST_COMMIT=${{ github.event.pull_request.head.sha || github.sha }}
          SHORT_COMMIT=${LATEST_COMMIT:0:8}
          
          # Handle both PR events and manual workflow dispatch
          if [ -n "$PR_NUMBER" ]; then
            PR_URL="https://github.com/$SOURCE_REPOSITORY/pull/$PR_NUMBER"
            BRANCH_NAME="theme-update/pr-$PR_NUMBER-$SHORT_COMMIT"
            PR_TITLE="preview: theme PR #$PR_NUMBER ($SHORT_COMMIT)"
          else
            # For manual workflow dispatch, use branch name instead
            BRANCH_REF="${{ github.head_ref || github.ref_name }}"
            PR_URL="https://github.com/$SOURCE_REPOSITORY/tree/$BRANCH_REF"
            BRANCH_NAME="theme-update/branch-$BRANCH_REF-$SHORT_COMMIT"
            PR_TITLE="preview: theme branch $BRANCH_REF ($SHORT_COMMIT)"
          fi
          
          BASE_BRANCH="main"
          ASSIGNEE="zetxek"

          echo "Latest commit: $LATEST_COMMIT"
          echo "Short commit: $SHORT_COMMIT"
          echo "Branch name: $BRANCH_NAME"
          echo "PR URL: $PR_URL"
          if [ -n "$PR_NUMBER" ]; then
            echo "PR Number: $PR_NUMBER"
          else
            echo "Manual workflow dispatch - no PR number"
          fi

          git config --global --add --bool push.autoSetupRemote true

          # Verify source commit exists
          cd source-repo
          if ! git cat-file -e $LATEST_COMMIT; then
            echo "Error: Commit $LATEST_COMMIT does not exist in source repository"
            exit 1
          fi
          echo "✅ Verified commit $LATEST_COMMIT exists in source repository"
          
          # Switch to demo repository
          cd ../demo-repo

          # Setup git identity
          git config user.email "actions@github.com"
          git config user.name "GitHub Actions - update theme module"

          # Create feature branch
          git checkout -b $BRANCH_NAME

          # Initialize Hugo module if needed
          if [ ! -f "go.mod" ]; then
            hugo mod init github.com/zetxek/adritian-demo
          fi

          # Clean up any existing invalid module references
          if [ -f "go.mod" ]; then
            echo "Cleaning up existing go.mod..."
            # Remove any existing theme references that might have invalid revisions
            grep -v 'github.com/zetxek/adritian-free-hugo-theme' go.mod > go.mod.tmp || touch go.mod.tmp
            mv go.mod.tmp go.mod
            # Clean up any existing go.sum entries
            if [ -f "go.sum" ]; then
              grep -v 'github.com/zetxek/adritian-free-hugo-theme' go.sum > go.sum.tmp || touch go.sum.tmp
              mv go.sum.tmp go.sum
            fi
          fi

          # Get the theme from the PR branch - use branch name instead of commit for better reliability
          BRANCH_NAME_THEME="${{ github.head_ref || github.ref_name }}"
          echo "Using theme branch: $BRANCH_NAME_THEME"
          
          # Try to get the specific commit first, fallback to branch if commit is not available
          echo "Attempting to get theme with commit: $LATEST_COMMIT"
          if hugo mod get github.com/zetxek/adritian-free-hugo-theme@$LATEST_COMMIT; then
            echo "✅ Successfully got theme with commit hash"
          else
            echo "Failed to get specific commit, trying branch instead..."
            echo "Attempting to get theme with branch: $BRANCH_NAME_THEME"
            if hugo mod get github.com/zetxek/adritian-free-hugo-theme@$BRANCH_NAME_THEME; then
              echo "✅ Successfully got theme with branch name"
            else
              echo "❌ Failed to get theme with both commit and branch, trying main branch as last resort..."
              hugo mod get github.com/zetxek/adritian-free-hugo-theme@main
            fi
          fi
          
          hugo mod tidy

          # Commit changes
          git add go.mod go.sum
          if [ -n "$PR_NUMBER" ]; then
            COMMIT_MSG="preview: theme PR #$PR_NUMBER ($SHORT_COMMIT)"
          else
            BRANCH_REF="${{ github.head_ref || github.ref_name }}"
            COMMIT_MSG="preview: theme branch $BRANCH_REF ($SHORT_COMMIT)"
          fi
          git commit -m "$COMMIT_MSG" && git push --force || echo "No changes to commit"

          # Push branch
          git push origin $BRANCH_NAME --force

          # Setup GitHub CLI
          echo "${{ secrets.PRIVATE_TOKEN_GITHUB }}" > token.txt
          gh auth login --with-token < token.txt

          # Check if PR exists
          PR_EXISTS=$(gh pr list --state open --base $BASE_BRANCH --head $BRANCH_NAME --json number | jq '.[0].number // empty')
          echo "PR_EXISTS: $PR_EXISTS"

          if [ -n "$PR_EXISTS" ]; then
            echo "PR Exists. Updating pull-request..."
            gh pr view
            echo "✅ Pull-request updated!"
            # TODO: update the PR body with the latest commit
            # Add a comment to the PR with the update
            gh pr comment $PR_EXISTS --body "Updated PR to last commit in source repo: \`$LATEST_COMMIT\`"
          else
            echo "✨ Creating new pull-request..."
            if [ -n "$PR_NUMBER" ]; then
              PR_BODY="⚠️ The source PR is not merged yet - this is a preview PR created to test the theme update with a vercel preview URL.
              - Last commit: \`$LATEST_COMMIT\`
              - Source PR: $PR_URL
              - 🔗 Triggered by https://github.com/zetxek/adritian-free-hugo-theme/actions/workflows/update-demo-pr.yml"
            else
              BRANCH_REF="${{ github.head_ref || github.ref_name }}"
              PR_BODY="⚠️ This is a preview PR created to test the theme update from branch \`$BRANCH_REF\` with a vercel preview URL.
              - Last commit: \`$LATEST_COMMIT\`
              - Source branch: $PR_URL
              - 🔗 Triggered by https://github.com/zetxek/adritian-free-hugo-theme/actions/workflows/update-demo-pr.yml"
            fi

            PR_RESULT=$(gh pr create \
              --title "$PR_TITLE" \
              --body "$PR_BODY" \
              --head $BRANCH_NAME \
              --base $BASE_BRANCH \
              --assignee $ASSIGNEE \
              --label preview)
            
            if [ $? -ne 0 ]; then
              echo "Error creating PR: $PR_RESULT"
              exit 0
            fi

            echo "✅ Pull-request created!"
          fi

          
