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

if ! command -v jq >/dev/null 2>&1; then
  echo "Error: jq is required"
  exit 1
fi

if ! command -v agent >/dev/null 2>&1; then
  echo "Error: Cursor agent CLI not found in PATH"
  exit 1
fi

for file in comment.txt context.json; do
  if [ ! -f "$file" ]; then
    echo "Error: $file not found"
    exit 1
  fi
done

REPO_FULL_NAME=$(jq -r '.repository.full_name' context.json)
COMMENT_USER=$(jq -r '.comment.user' context.json)
ISSUE_NUMBER=$(jq -r '.issue.number' context.json)

if [ "$(jq -r '.issue.is_pull_request' context.json)" = "true" ]; then
  ISSUE_TYPE="pull request"
else
  ISSUE_TYPE="issue"
fi

# Case-insensitive strip of @cursor mention and leading whitespace
COMMENT=$(sed -E 's/.*@cursor//i' comment.txt | sed 's/^[[:space:]]*//')
CONTEXT=$(cat context.json)

mkdir -p "$HOME/.cursor"
jq -n \
  --arg cmd "/tmp/gitea-mcp/gitea-mcp" \
  --arg host "${GITEA_BASE_URL}" \
  --arg token "${GITEA_ACCESS_TOKEN}" \
  '{
    mcpServers: {
      gitea: {
        command: $cmd,
        args: ["-t", "stdio"],
        env: {
          GITEA_HOST: $host,
          GITEA_ACCESS_TOKEN: $token
        }
      }
    }
  }' > "$HOME/.cursor/mcp.json"

git config user.name "cursor"
git config user.email "cursor@users.noreply.gitea.schwenk.online"

PROMPT="You are an autonomous software engineering agent called cursor for repository: ${REPO_FULL_NAME}

## CONTEXT INFORMATION
${CONTEXT}

## USER REQUEST
@${COMMENT_USER} has requested:
${COMMENT}

## AVAILABLE TOOLS

You have full access to Gitea via MCP tools. Use them to:
- Fetch all comments on this ${ISSUE_TYPE} to understand the full conversation history
- If this is a PR: get the diff, changed files, and commits
- Read files from the repository to understand the codebase
- Create branches, make commits, and create pull requests
- Post comments with your findings or questions

## YOUR INSTRUCTIONS

1. **Gather More Context (if needed):**
   - Let the user know you've received the request and that you now start working on it.
   - Use MCP tools to fetch all comments on ${ISSUE_TYPE} #${ISSUE_NUMBER} to understand the discussion
   - If this is a PR, use MCP tools to get the PR details, diff, and changed files
   - Read relevant files from the codebase if needed to understand the context

2. **Analyze the Request:**
   - Understand what the user is asking for
   - Consider the context of the ${ISSUE_TYPE} and previous discussion
   - If the request is unclear, ask for clarification via a comment

3. **Take Action:**
   - If implementing code: create a feature branch and open a pull request
   - If reviewing code: post a structured review in the pull request
   - If answering questions: provide helpful, accurate information
   - If the request is not feasible or safe: explain why and suggest alternatives
   - Use the MCP tool to create a Pull Request if needed

4. **Let the user know you've completed the request**
   - Post your response as a comment on the ${ISSUE_TYPE}
   - If the request is not feasible or safe: explain why and suggest alternatives

## SAFETY RULES

- NEVER push directly to protected branches (main, master, etc.)
- Always use MCP tools for Gitea interactions
- Be minimal, precise, and safe in your actions"

echo "Running Cursor agent for ${REPO_FULL_NAME} ${ISSUE_TYPE} #${ISSUE_NUMBER} (model: ${AI_MODEL})"

timeout 30m agent -p "$PROMPT" --force --model "${AI_MODEL}" --output-format=text

echo "Cursor agent completed."
