name: "GitHub: Issue Comment Created"
on:
  issue_comment:
    types:
      - created
concurrency:
  group: ${{ github.workflow }}-${{ github.event.issue.number }}
  cancel-in-progress: true
jobs:
  guard:
    if: format('{0}', github.event.issue.pull_request != null) != 'true' && github.event.issue.state == 'open' && github.event.comment.user.type != 'Bot'
    runs-on: ubuntu-latest
    env:
      OUTPUT_FORMAT: terminal
    outputs:
      should_run: ${{ steps.guard_result.outputs.should_run }}
    permissions:
      contents: read
    steps:
      - name: Preflight
        env:
          POE_CODE_AGENT_APP_ID: ${{ secrets.POE_CODE_AGENT_APP_ID }}
          POE_CODE_AGENT_PRIVATE_KEY: ${{ secrets.POE_CODE_AGENT_PRIVATE_KEY }}
          POE_API_KEY: ${{ secrets.POE_API_KEY }}
        run: |
          missing=()
          is_blank() { [[ -z "${1//[[:space:]]/}" ]]; }
          is_blank "$POE_CODE_AGENT_APP_ID" && missing+=("POE_CODE_AGENT_APP_ID")
          is_blank "$POE_CODE_AGENT_PRIVATE_KEY" && missing+=("POE_CODE_AGENT_PRIVATE_KEY")
          is_blank "$POE_API_KEY" && missing+=("POE_API_KEY")
          if [ ${#missing[@]} -gt 0 ]; then
            for name in "${missing[@]}"; do
              echo "::error::Missing required secret: $name — add it in Settings → Secrets and variables → Actions"
            done
            exit 1
          fi
      - uses: actions/create-github-app-token@v1
        id: app-token
        with:
          app-id: ${{ secrets.POE_CODE_AGENT_APP_ID }}
          private-key: ${{ secrets.POE_CODE_AGENT_PRIVATE_KEY }}
      - uses: actions/checkout@v4
        with:
          token: ${{ steps.app-token.outputs.token }}
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm install -g poe-code@latest
      - id: allow_check
        continue-on-error: true
        run: poe-code github-workflows require-user-allow github-issue-comment-created
        env:
          POE_CODE_STDERR_LOGS: "1"
          COMMENT_AUTHOR_ASSOCIATION: ${{ github.event.comment.author_association }}
      - id: prefix_check
        continue-on-error: true
        run: poe-code github-workflows require-comment-prefix github-issue-comment-created
        env:
          POE_CODE_STDERR_LOGS: "1"
          COMMENT_BODY: ${{ github.event.comment.body }}
      - id: guard_result
        run: |
          if [ "${{ steps.allow_check.outcome }}" = "success" ] && [ "${{ steps.prefix_check.outcome }}" = "success" ]; then
            echo "should_run=true" >> "$GITHUB_OUTPUT"
          else
            echo "should_run=false" >> "$GITHUB_OUTPUT"
          fi
  run:
    needs: guard
    if: needs.guard.outputs.should_run == 'true'
    runs-on: ubuntu-latest
    env:
      OUTPUT_FORMAT: terminal
    permissions:
      contents: write
      issues: write
      pull-requests: write
    steps:
      - name: Preflight
        env:
          POE_CODE_AGENT_APP_ID: ${{ secrets.POE_CODE_AGENT_APP_ID }}
          POE_CODE_AGENT_PRIVATE_KEY: ${{ secrets.POE_CODE_AGENT_PRIVATE_KEY }}
          POE_API_KEY: ${{ secrets.POE_API_KEY }}
        run: |
          missing=()
          is_blank() { [[ -z "${1//[[:space:]]/}" ]]; }
          is_blank "$POE_CODE_AGENT_APP_ID" && missing+=("POE_CODE_AGENT_APP_ID")
          is_blank "$POE_CODE_AGENT_PRIVATE_KEY" && missing+=("POE_CODE_AGENT_PRIVATE_KEY")
          is_blank "$POE_API_KEY" && missing+=("POE_API_KEY")
          if [ ${#missing[@]} -gt 0 ]; then
            for name in "${missing[@]}"; do
              echo "::error::Missing required secret: $name — add it in Settings → Secrets and variables → Actions"
            done
            exit 1
          fi
      - uses: actions/create-github-app-token@v1
        id: app-token
        with:
          app-id: ${{ secrets.POE_CODE_AGENT_APP_ID }}
          private-key: ${{ secrets.POE_CODE_AGENT_PRIVATE_KEY }}
      - uses: actions/checkout@v4
        with:
          token: ${{ steps.app-token.outputs.token }}
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm install -g poe-code@latest
      - id: pr_context
        uses: actions/github-script@v7
        with:
          github-token: ${{ steps.app-token.outputs.token }}
          script: |
            if ("${{ github.event.issue.pull_request != null }}" !== "true") {
              core.setOutput("pr_number", "");
              core.setOutput("pr_title", "");
              core.setOutput("pr_author", "");
              core.setOutput("head_ref", "");
              return;
            }

            const response = await github.rest.pulls.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: Number("${{ github.event.issue.number }}")
            });

            const headRepo = response.data.head.repo?.full_name ?? "";
            const currentRepo = `${context.repo.owner}/${context.repo.repo}`;
            const isSameRepo = headRepo === currentRepo;

            core.setOutput("pr_number", String(response.data.number ?? ""));
            core.setOutput("pr_title", response.data.title ?? "");
            core.setOutput("pr_author", response.data.user?.login ?? "");
            core.setOutput("head_ref", isSameRepo ? (response.data.head.ref ?? "") : "");
      - id: add_in_progress_reaction
        continue-on-error: true
        uses: actions/github-script@v7
        with:
          github-token: ${{ steps.app-token.outputs.token }}
          script: |
            const response = await github.rest.reactions.createForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: Number("${{ github.event.comment.id }}"),
              content: "eyes"
            });
            core.setOutput("reaction_id", String(response.data.id ?? ""));
      - if: steps.pr_context.outputs.head_ref != ''
        id: checkout_pr_branch
        uses: actions/checkout@v4
        with:
          ref: ${{ steps.pr_context.outputs.head_ref }}
          token: ${{ steps.app-token.outputs.token }}
      - if: steps.pr_context.outputs.head_ref == ''
        id: checkout_default_branch
        uses: actions/checkout@v4
        with:
          token: ${{ steps.app-token.outputs.token }}
      - name: Configure git identity for GitHub App
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token }}
          APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
        run: |
          USER_ID=$(gh api "/users/${APP_SLUG}[bot]" --jq .id)
          git config --global user.name "${APP_SLUG}[bot]"
          git config --global user.email "${USER_ID}+${APP_SLUG}[bot]@users.noreply.github.com"
      - run: poe-code github-workflows prepare github-issue-comment-created
        env:
          POE_CODE_STDERR_LOGS: "1"
          POE_API_KEY: ${{ secrets.POE_API_KEY }}
      - run: poe-code github-workflows github-issue-comment-created --yes
        env:
          POE_CODE_STDERR_LOGS: "1"
          POE_API_KEY: ${{ secrets.POE_API_KEY }}
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
          ISSUE_NUMBER: ${{ github.event.issue.number }}
          PR_NUMBER: ${{ steps.pr_context.outputs.pr_number }}
          PR_TITLE: ${{ steps.pr_context.outputs.pr_title }}
          PR_AUTHOR: ${{ steps.pr_context.outputs.pr_author }}
          COMMENT_BODY: ${{ github.event.comment.body }}
          COMMENT_AUTHOR: ${{ github.event.comment.user.login }}
          GITHUB_REPOSITORY: ${{ github.repository }}
      - id: remove_in_progress_reaction
        if: always() && steps.add_in_progress_reaction.outputs.reaction_id != ''
        continue-on-error: true
        uses: actions/github-script@v7
        with:
          github-token: ${{ steps.app-token.outputs.token }}
          script: |
            await github.rest.reactions.deleteForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: Number("${{ github.event.comment.id }}"),
              reaction_id: Number("${{ steps.add_in_progress_reaction.outputs.reaction_id }}")
            });
