#!/usr/bin/env bash
set -euo pipefail

RESULT_FILE="${1:-results.json}"

# Check if result file exists
if [ ! -f "$RESULT_FILE" ]; then
    echo "Error: Result file not found: $RESULT_FILE"
    exit 1
fi

# Check if we have any results
if [ ! -s "$RESULT_FILE" ] || [ "$(jq length "$RESULT_FILE")" -eq 0 ]; then
    echo "No results to post"
    exit 0
fi

# Extract PR number from GitHub Actions environment
if [ -n "${GITHUB_EVENT_NUMBER:-}" ]; then
    # Use the event number if available (for pull_request events)
    PR_NUMBER="$GITHUB_EVENT_NUMBER"
elif [ -n "${GITHUB_REF#refs/pull/}" ] && [ "$GITHUB_REF" != "${GITHUB_REF#refs/pull/}" ]; then
    # Extract from refs/pull/NUMBER/merge format
    PR_NUMBER="${GITHUB_REF#refs/pull/}"
    PR_NUMBER="${PR_NUMBER%/merge}"
else
    echo "Error: Could not extract PR number from GitHub environment"
    echo "GITHUB_EVENT_NUMBER: ${GITHUB_EVENT_NUMBER:-not set}"
    echo "GITHUB_REF: ${GITHUB_REF:-not set}"
    echo "GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME:-not set}"
    echo "This action should only run on pull request events"
    exit 1
fi

echo "Posting results to PR #$PR_NUMBER"
echo "Debug info:"
echo "  GITHUB_EVENT_NUMBER: ${GITHUB_EVENT_NUMBER:-not set}"
echo "  GITHUB_REF: ${GITHUB_REF:-not set}"
echo "  GITHUB_EVENT_NAME: ${GITHUB_EVENT_NAME:-not set}"
echo "  GITHUB_REPOSITORY: ${GITHUB_REPOSITORY:-not set}"

# Build comment body
COMMENT_BODY=""

# Process each result
while read -r LINE; do
    RULE=$(echo "$LINE" | jq -r '.rule')
    OUTPUT=$(echo "$LINE" | jq -r '.output')
    
    # Debug: Show what we're processing
    echo "Processing rule: $RULE"
    echo "Output length: ${#OUTPUT} characters"
    echo "First 100 chars: ${OUTPUT:0:100}"
    
    # Don't escape the output since agents return markdown-formatted text
    # Just use the raw output to preserve markdown formatting

    COMMENT_BODY+="## 🔍 $RULE Analysis Result"$'\n\n'
    COMMENT_BODY+="$OUTPUT"$'\n\n'
done < <(jq -c '.[]' "$RESULT_FILE")

# Add footer
COMMENT_BODY+="---"$'\n'
COMMENT_BODY+="*Generated by [AutoAgent](https://github.com/erans/autoagent) v1.0*"

echo "Comment body prepared (${#COMMENT_BODY} characters)"
echo "DEBUG: Final comment body preview:"
echo "--- START COMMENT PREVIEW ---"
echo -e "$COMMENT_BODY"
echo "--- END COMMENT PREVIEW ---"

# Post comment using GitHub CLI
if command -v gh >/dev/null 2>&1; then
    # Set GH_TOKEN from GITHUB_TOKEN for GitHub CLI
    if [ -n "${GITHUB_TOKEN:-}" ]; then
        export GH_TOKEN="$GITHUB_TOKEN"
        
        # Create temporary file for comment body (similar to cursor-agent approach)
        COMMENT_FILE_TEMP=$(mktemp)
        echo "DEBUG: Creating temporary comment file: $COMMENT_FILE_TEMP"
        
        # Write comment body to temporary file
        printf '%s' "$COMMENT_BODY" > "$COMMENT_FILE_TEMP"
        
        # Debug: Show file size and first few lines
        echo "DEBUG: Comment file size: $(wc -c < "$COMMENT_FILE_TEMP") characters"
        echo "DEBUG: First 200 chars of comment file:"
        head -c 200 "$COMMENT_FILE_TEMP"
        echo ""
        echo "DEBUG: --- END COMMENT FILE PREVIEW ---"
        
        # Post comment using file input (pipe approach like cursor-agent)
        echo "DEBUG: Posting comment using: gh pr comment $PR_NUMBER --body-file $COMMENT_FILE_TEMP"
        if gh pr comment "$PR_NUMBER" --body-file "$COMMENT_FILE_TEMP"; then
            echo "Comment posted successfully to PR #$PR_NUMBER"
        else
            echo "Error: Failed to post comment to PR #$PR_NUMBER"
            echo "Comment content that failed to post:"
            echo "---"
            cat "$COMMENT_FILE_TEMP"
            echo "---"
            rm -f "$COMMENT_FILE_TEMP"
            exit 1
        fi
        
        # Clean up temporary file
        rm -f "$COMMENT_FILE_TEMP"
        echo "DEBUG: Cleaned up temporary comment file"
        
    else
        echo "Error: GITHUB_TOKEN environment variable is not set."
        echo "This action requires the GITHUB_TOKEN to post comments."
        echo "Comment that would have been posted:"
        echo "---"
        printf '%s' "$COMMENT_BODY"
        echo "---"
        exit 1
    fi
else
    echo "Error: GitHub CLI (gh) not found. Cannot post comment."
    echo "Please ensure the GitHub CLI is available in the runner environment."
    echo "Comment that would have been posted:"
    echo "---"
    printf '%s' "$COMMENT_BODY"
    echo "---"
    exit 1
fi
