name: 🆗 Ok to preview

on:
  pull_request_target:
    types: [labeled]

jobs:
  ok-to-preview:
    if: ${{ github.event.label.name == 'ok-to-preview' }}
    runs-on: ubuntu-latest
    steps:

    - name: Get changed files
      #uses: lots0logs/gh-action-get-changed-files@2.1.4
      uses: raik0707/gh-action-get-changed-files@5819313b441087a2e632d14773a12c6e9bc72912 # feature/support-pr-target-event - Remove as soon as PR is merged to lots0logs
      with:
        token: ${{ secrets.GITHUB_TOKEN }}

    - name: Get comment message
      id: get-comment-message
      run: |
        import os, json, textwrap

        all_files_path = os.path.join(os.environ["HOME"], "files.json")
        event_json_path = os.environ["GITHUB_EVENT_PATH"]

        with open(all_files_path) as f:
            all_files = json.load(f)

        with open(event_json_path) as f:
            event_data = json.load(f)

        links = [
          "https://strawberry.rocks/docs/pr/{pr_number}/{path}".format(
            pr_number=event_data["number"],
            path=file.replace(".md", "").replace("docs/", "")
          )
          for file in all_files
          if file.startswith("docs/") and file.endswith(".md")
        ]

        message = textwrap.dedent(
          """
          Hi 👋 You can find a preview of the docs here:

          {links}
          """
        ).format(links="\n".join(links))

        message = message.replace("%", "%25").replace("\n", "%0A").replace("\r", "%0D")
        output = "::set-output name=message::{}".format(message)

        print(output)
      shell: python

    - name: Create comment
      uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5
      with:
        issue-number: ${{ github.event.number }}
        body: ${{ steps.get-comment-message.outputs.message }}
