name: 'Check Issue Completeness'

on:
  issues:
    types:
      - 'opened'
      - 'edited'

permissions:
  contents: 'read'
  issues: 'write'

jobs:
  check-issue-info:
    timeout-minutes: 2
    if: |-
      ${{ github.repository == 'QwenLM/qwen-code' && contains(github.event.issue.labels.*.name, 'type/bug') }}
    runs-on: 'ubuntu-latest'
    steps:
      - name: 'Check for Client Information'
        id: 'check_info'
        env:
          ISSUE_BODY: '${{ github.event.issue.body }}'
        run: |-
          echo "Checking issue body for required information..."

          # Convert issue body to lowercase for case-insensitive matching
          ISSUE_BODY_LOWER=$(echo "$ISSUE_BODY" | tr '[:upper:]' '[:lower:]')

          # Initialize flags
          HAS_VERSION=false
          HAS_OS_INFO=false
          HAS_AUTH_METHOD=false
          HAS_ABOUT_OUTPUT=false
          MISSING_INFO=()

          # Check for /about command output by looking for its characteristic fields
          # The /about output contains: CLI Version, Git Commit, Model, Sandbox, OS, Auth Method
          if echo "$ISSUE_BODY_LOWER" | grep -qE 'cli version.*[0-9]+\.[0-9]+\.[0-9]+'; then
            HAS_ABOUT_OUTPUT=true
            HAS_VERSION=true
          fi

          # If full /about output is not detected, check individual components
          if [ "$HAS_ABOUT_OUTPUT" = false ]; then
            # Check for version information (various formats)
            if echo "$ISSUE_BODY_LOWER" | grep -qE '(cli version|version|v)[[:space:]]*[0-9]+\.[0-9]+\.[0-9]+'; then
              HAS_VERSION=true
            fi

            # Check for OS information
            if echo "$ISSUE_BODY_LOWER" | grep -qE '(^os[[:space:]]|macos|windows|linux|ubuntu|debian|fedora|arch|darwin|win32|platform)'; then
              HAS_OS_INFO=true
            fi

            # Check for Auth Method information
            if echo "$ISSUE_BODY_LOWER" | grep -qE '(auth method|authentication|login|qwen-oauth|api.?config|oauth)'; then
              HAS_AUTH_METHOD=true
            fi
          else
            # If /about output is present, assume it contains OS and auth info
            HAS_OS_INFO=true
            HAS_AUTH_METHOD=true
          fi

          # Determine what's missing
          if [ "$HAS_ABOUT_OUTPUT" = false ]; then
            if [ "$HAS_VERSION" = false ]; then
              MISSING_INFO+=("Qwen Code version")
            fi
            if [ "$HAS_OS_INFO" = false ]; then
              MISSING_INFO+=("operating system information")
            fi
            if [ "$HAS_AUTH_METHOD" = false ]; then
              MISSING_INFO+=("authentication/login method")
            fi
            # Suggest providing /about output for completeness
            if [ "$HAS_VERSION" = false ] || [ "$HAS_OS_INFO" = false ] || [ "$HAS_AUTH_METHOD" = false ]; then
              MISSING_INFO+=("full output of the \`/about\` command (recommended)")
            fi
          fi

          # Set output variables
          if [ ${#MISSING_INFO[@]} -eq 0 ]; then
            echo "info_complete=true" >> "$GITHUB_OUTPUT"
            echo "All required information is present."
          else
            echo "info_complete=false" >> "$GITHUB_OUTPUT"
            # Join array elements with comma
            MISSING_LIST=$(IFS=','; echo "${MISSING_INFO[*]}")
            echo "missing_info=$MISSING_LIST" >> "$GITHUB_OUTPUT"
            echo "Missing information: $MISSING_LIST"
          fi

      - name: 'Comment on Issue if Information is Missing'
        if: |-
          ${{ steps.check_info.outputs.info_complete == 'false' }}
        uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea' # ratchet:actions/github-script@v7
        env:
          MISSING_INFO: '${{ steps.check_info.outputs.missing_info }}'
        with:
          github-token: '${{ secrets.GITHUB_TOKEN }}'
          script: |
            const missingInfo = process.env.MISSING_INFO.split(',');
            const missingList = missingInfo.map(item => `- ${item}`).join('\n');

            const comments = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });

            const botComment = comments.data.find(comment =>
              comment.user.type === 'Bot' &&
              comment.body.includes('Missing Required Information')
            );

            const commentBody = `### ⚠️ Missing Required Information

            Thank you for reporting this issue! To help us investigate and resolve this problem more effectively, we need some additional information:

            ${missingList}

            ### How to provide this information:

            Please run the following command and paste the complete output:

            \`\`\`bash
            qwen
            # Then in the interactive CLI, run:
            /about
            \`\`\`

            The output should look like:
            \`\`\`
            CLI Version             0.0.14
            Git Commit              9a0cb64a
            Model                   coder-model
            Sandbox                 no sandbox
            OS                      darwin
            Auth Method             qwen-oauth
            \`\`\`

            Once you provide this information, we'll be able to assist you better. Thank you! 🙏`;

            if (botComment) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: commentBody
              });
              console.log('Updated existing comment about missing information.');
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: commentBody
              });
              console.log('Created new comment about missing information.');
            }

      - name: 'Add status/need-information Label'
        if: |-
          ${{ steps.check_info.outputs.info_complete == 'false' }}
        uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea' # ratchet:actions/github-script@v7
        with:
          github-token: '${{ secrets.GITHUB_TOKEN }}'
          script: |
            await github.rest.issues.addLabels({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              labels: ['status/need-information']
            });
            console.log('Added status/need-information label.');

      - name: 'Remove status/need-information Label if Complete'
        if: |-
          ${{ steps.check_info.outputs.info_complete == 'true' }}
        uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea' # ratchet:actions/github-script@v7
        continue-on-error: true
        with:
          github-token: '${{ secrets.GITHUB_TOKEN }}'
          script: |
            try {
              await github.rest.issues.removeLabel({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                name: 'status/need-information'
              });
              console.log('Removed status/need-information label as information is now complete.');
            } catch (error) {
              if (error.status === 404) {
                console.log('Label not found on issue, nothing to remove.');
              } else {
                throw error;
              }
            }
