name: Update JSON Date

on:
  push:
    branches:
      - main
    paths:
      - 'frontend/public/json/**.json'
  workflow_dispatch: 

jobs:
  update-app-files:
    runs-on: runner-cluster-htl-set

    permissions:
      contents: write
      pull-requests: write

    steps:
      - name: Generate a token
        id: generate-token
        uses: actions/create-github-app-token@v1
        with:
          app-id: ${{ vars.APP_ID }}
          private-key: ${{ secrets.APP_PRIVATE_KEY }}

      - name: Generate dynamic branch name
        id: timestamp
        run: echo "BRANCH_NAME=pr-update-json-$(date +'%Y%m%d%H%M%S')" >> $GITHUB_ENV
      
      - name: Set up GH_TOKEN
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo "GH_TOKEN=${GH_TOKEN}" >> $GITHUB_ENV

      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 2  # Ensure we have the last two commits

      - name: Get Previous Commit
        id: prev_commit
        run: |
          PREV_COMMIT=$(git rev-parse HEAD^)
          echo "Previous commit: $PREV_COMMIT"
          echo "prev_commit=$PREV_COMMIT" >> $GITHUB_ENV

      - name: Get Newly Added JSON Files
        id: new_json_files
        run: |
          git diff --name-only --diff-filter=A ${{ env.prev_commit }} HEAD | grep '^frontend/public/json/.*\.json$' > new_files.txt || true
          echo "New files detected:"
          cat new_files.txt || echo "No new files."

      - name: Disable file mode changes
        run: git config core.fileMode false

      - name: Set up Git
        run: |
          git config --global user.name "GitHub Actions"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"

      - name: Change JSON Date
        id: change-json-date
        run: |
          current_date=$(date +"%Y-%m-%d")
          while IFS= read -r file; do
            # Skip empty lines
            [[ -z "$file" ]] && continue

            if [[ -f "$file" ]]; then
              echo "Processing $file..."
              current_json_date=$(jq -r '.date_created // empty' "$file")
              if [[ -z "$current_json_date" || "$current_json_date" != "$current_date" ]]; then
                echo "Updating $file with date $current_date"
                jq --arg date "$current_date" '.date_created = $date' "$file" > temp.json && mv temp.json "$file"
              else
                echo "Date in $file is already up to date."
              fi
            else
              echo "Warning: File $file not found!"
            fi
          done < new_files.txt
          rm new_files.txt

      - name: Check if there are any changes
        run: |
          echo "Checking for changes..."
          git add -A  
          git status
          if git diff --cached --quiet; then
            echo "No changes detected."
            echo "changed=false" >> "$GITHUB_ENV"
          else
            echo "Changes detected:"
            git diff --stat --cached
            echo "changed=true" >> "$GITHUB_ENV"
          fi

      # Step 7: Commit and create PR if changes exist
      - name: Commit and create PR if changes exist
        if: env.changed == 'true'
        run: |
         
          
          git commit -m "Update date in json"
          git checkout -b ${{ env.BRANCH_NAME }}
          git push origin ${{ env.BRANCH_NAME }}

          gh pr create --title "[core] update date in json" \
                       --body "This PR is auto-generated by a GitHub Action to update the date in json." \
                       --head ${{ env.BRANCH_NAME }} \
                       --base main \
                       --label "automated pr"
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}

      - name: Approve pull request
        if: env.changed == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_NUMBER=$(gh pr list --head "${{ env.BRANCH_NAME }}" --json number --jq '.[].number')
          if [ -n "$PR_NUMBER" ]; then
            gh pr review $PR_NUMBER --approve
          fi

      - name: No changes detected
        if: env.changed == 'false'
        run: echo "No changes to commit. Workflow completed successfully."
