name: Log GitHub Issue Events

on:
  issues:
    types: [opened, closed]

jobs:
  log-issue-created:
    if: github.event.action == 'opened'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      issues: read

    steps:
      - name: Log issue creation to Statsig
        env:
          STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
        run: |
          ISSUE_NUMBER=${{ github.event.issue.number }}
          REPO=${{ github.repository }}
          ISSUE_TITLE=$(echo '${{ github.event.issue.title }}' | sed "s/'/'\\\\''/g")
          AUTHOR="${{ github.event.issue.user.login }}"
          CREATED_AT="${{ github.event.issue.created_at }}"
          
          if [ -z "$STATSIG_API_KEY" ]; then
            echo "STATSIG_API_KEY not found, skipping Statsig logging"
            exit 0
          fi
          
          # Prepare the event payload
          EVENT_PAYLOAD=$(jq -n \
            --arg issue_number "$ISSUE_NUMBER" \
            --arg repo "$REPO" \
            --arg title "$ISSUE_TITLE" \
            --arg author "$AUTHOR" \
            --arg created_at "$CREATED_AT" \
            '{
              events: [{
                eventName: "github_issue_created",
                value: 1,
                metadata: {
                  repository: $repo,
                  issue_number: ($issue_number | tonumber),
                  issue_title: $title,
                  issue_author: $author,
                  created_at: $created_at
                },
                time: (now | floor | tostring)
              }]
            }')
          
          # Send to Statsig API
          echo "Logging issue creation to Statsig for issue #${ISSUE_NUMBER}"
          
          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
            -H "Content-Type: application/json" \
            -H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
            -d "$EVENT_PAYLOAD")
          
          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
          BODY=$(echo "$RESPONSE" | head -n-1)
          
          if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
            echo "Successfully logged issue creation for issue #${ISSUE_NUMBER}"
          else
            echo "Failed to log issue creation for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
          fi

  log-issue-closed:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      issues: read

    steps:
      - name: Log issue closure to Statsig
        env:
          STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          ISSUE_NUMBER=${{ github.event.issue.number }}
          REPO=${{ github.repository }}
          ISSUE_TITLE=$(echo '${{ github.event.issue.title }}' | sed "s/'/'\\\\''/g")
          CLOSED_BY="${{ github.event.issue.closed_by.login }}"
          CLOSED_AT="${{ github.event.issue.closed_at }}"
          STATE_REASON="${{ github.event.issue.state_reason }}"
          
          if [ -z "$STATSIG_API_KEY" ]; then
            echo "STATSIG_API_KEY not found, skipping Statsig logging"
            exit 0
          fi
          
          # Get additional issue data via GitHub API
          echo "Fetching additional issue data for #${ISSUE_NUMBER}"
          ISSUE_DATA=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${REPO}/issues/${ISSUE_NUMBER}")
          
          COMMENTS_COUNT=$(echo "$ISSUE_DATA" | jq -r '.comments')
          
          # Get reactions data
          REACTIONS_DATA=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${REPO}/issues/${ISSUE_NUMBER}/reactions")
          
          REACTIONS_COUNT=$(echo "$REACTIONS_DATA" | jq '. | length')
          
          # Check if issue was closed automatically (by checking if closed_by is a bot)
          CLOSED_AUTOMATICALLY="false"
          if [[ "$CLOSED_BY" == *"[bot]"* ]]; then
            CLOSED_AUTOMATICALLY="true"
          fi
          
          # Check if closed as duplicate by state_reason
          CLOSED_AS_DUPLICATE="false"
          if [ "$STATE_REASON" = "duplicate" ]; then
            CLOSED_AS_DUPLICATE="true"
          fi
          
          # Prepare the event payload
          EVENT_PAYLOAD=$(jq -n \
            --arg issue_number "$ISSUE_NUMBER" \
            --arg repo "$REPO" \
            --arg title "$ISSUE_TITLE" \
            --arg closed_by "$CLOSED_BY" \
            --arg closed_at "$CLOSED_AT" \
            --arg state_reason "$STATE_REASON" \
            --arg comments_count "$COMMENTS_COUNT" \
            --arg reactions_count "$REACTIONS_COUNT" \
            --arg closed_automatically "$CLOSED_AUTOMATICALLY" \
            --arg closed_as_duplicate "$CLOSED_AS_DUPLICATE" \
            '{
              events: [{
                eventName: "github_issue_closed",
                value: 1,
                metadata: {
                  repository: $repo,
                  issue_number: ($issue_number | tonumber),
                  issue_title: $title,
                  closed_by: $closed_by,
                  closed_at: $closed_at,
                  state_reason: $state_reason,
                  comments_count: ($comments_count | tonumber),
                  reactions_count: ($reactions_count | tonumber),
                  closed_automatically: ($closed_automatically | test("true")),
                  closed_as_duplicate: ($closed_as_duplicate | test("true"))
                },
                time: (now | floor | tostring)
              }]
            }')
          
          # Send to Statsig API
          echo "Logging issue closure to Statsig for issue #${ISSUE_NUMBER}"
          
          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
            -H "Content-Type: application/json" \
            -H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
            -d "$EVENT_PAYLOAD")
          
          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
          BODY=$(echo "$RESPONSE" | head -n-1)
          
          if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
            echo "Successfully logged issue closure for issue #${ISSUE_NUMBER}"
            echo "Closed by: $CLOSED_BY"
            echo "Comments: $COMMENTS_COUNT"
            echo "Reactions: $REACTIONS_COUNT"
            echo "Closed automatically: $CLOSED_AUTOMATICALLY"
            echo "Closed as duplicate: $CLOSED_AS_DUPLICATE"
          else
            echo "Failed to log issue closure for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
          fi