# Copyright (C) 2025 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Update CODEOWNERS

on:
  schedule:
    # Run at 9:00 AM UTC on Monday, Wednesday, and Friday
    - cron: '0 9 * * 1,3,5'
  workflow_dispatch:  # Allow manual triggering

permissions:
  contents: write  # Needed to push branch for PR
  pull-requests: write  # Needed to create PR

jobs:
  update-codeowners:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: main  # Always use main branch to avoid running modified scripts from PRs
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.x'

      - name: Generate CODEOWNERS file
        run: |
          python3 tools/gen_github_codeowners

      - name: Check for changes
        id: check_changes
        run: |
          if git diff --quiet .github/CODEOWNERS; then
            echo "has_changes=false" >> $GITHUB_OUTPUT
          else
            echo "has_changes=true" >> $GITHUB_OUTPUT
          fi

      - name: Create Pull Request
        if: steps.check_changes.outputs.has_changes == 'true'
        uses: peter-evans/create-pull-request@v7
        with:
          commit-message: |
            Update .github/CODEOWNERS from OWNERS.github files

            This is an automated update generated from distributed OWNERS.github
            files throughout the repository.
          branch: dev/github-bot/update-codeowners
          delete-branch: true
          title: 'Update .github/CODEOWNERS from OWNERS.github files'
          body: |
            This PR automatically updates `.github/CODEOWNERS` based on the distributed `OWNERS.github` files in the repository.

            The changes reflect updates to code ownership as specified in the individual `OWNERS.github` files.

            This is an automated PR generated by the `update-codeowners` workflow.
          labels: automated
