# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  pull_request:
    branches: [main, develop]

name: code-review-gpt

jobs:
  code-review-gpt:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      PR_COMMENTS_URL: ${{ github.event.pull_request.comments_url }}
    steps:
      - uses: actions/checkout@v3

      - uses: r-lib/actions/setup-r@v2
        with:
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          cache-version: 2
          extra-packages: |
            any::chatgpt

      - name: code-review
        run: |
          GITHUB_BASE_REF <- paste0("origin/", Sys.getenv("GITHUB_BASE_REF"))
          GITHUB_HEAD_REF <- paste0("origin/", Sys.getenv("GITHUB_HEAD_REF"))
          system("git fetch origin")
          git_diff_cmnd <- paste("git diff", GITHUB_HEAD_REF, GITHUB_BASE_REF)
          diff <- system(git_diff_cmnd, intern = TRUE)
          prompt <- paste(
            paste0(
              "Between sextuple quotes is a GitHub PR created with `", git_diff_cmnd, "` command."
            ),
            "Please perform a code review on it.",
            "Only notify if you find any issues.",
            "If possible, specify on which files and lines you find the issues.",
            '""""""',
            paste(diff, collapse = "\n"),
            '""""""',
            sep = "\n"
          )
          code_review <- chatgpt::ask_chatgpt(prompt)
          httr::POST(
            Sys.getenv("PR_COMMENTS_URL"),
            httr::add_headers(Authorization = paste("token", Sys.getenv("GITHUB_PAT"))),
            encode = "json",
            body = list(body = code_review)
          )
        shell: Rscript {0}
