name: Triage Agent

on:
  issues:
    types: [labeled]

jobs:
  analyze:
    if: github.event.label.name == 'triage'
    runs-on: ubuntu-latest
    permissions:
      issues: write
      contents: read
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: |
          pip install uv
          uv sync

      - name: Generate repo structure
        run: |
          find libs apps -type f -name "*.py" | head -200 > /tmp/repo_files.txt
          echo "## Repo Structure" > /tmp/context.md
          cat /tmp/repo_files.txt >> /tmp/context.md

      - name: Search codebase for relevant files
        env:
          ISSUE_TITLE: ${{ github.event.issue.title }}
          ISSUE_BODY: ${{ github.event.issue.body }}
        run: |
          echo "## Relevant Code Snippets" > /tmp/relevant_code.md
          keywords=$(echo "$ISSUE_TITLE $ISSUE_BODY" | tr '[:upper:]' '[:lower:]' | grep -oE '[a-z_]{4,}' | sort -u | head -15)
          for kw in $keywords; do
            matches=$(grep -rl --include="*.py" "$kw" libs/ apps/ 2>/dev/null | head -5)
            for f in $matches; do
              echo "" >> /tmp/relevant_code.md
              echo "### $f" >> /tmp/relevant_code.md
              head -100 "$f" >> /tmp/relevant_code.md
            done
          done
          head -c 30000 /tmp/relevant_code.md > /tmp/rc_trimmed.md
          mv /tmp/rc_trimmed.md /tmp/relevant_code.md

      - name: Run tests
        continue-on-error: true
        run: |
          source .venv/bin/activate
          python -m pytest --tb=short 2>&1 | tail -50 > /tmp/test_output.txt

      - name: Analyze with GPT 5.2
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          ISSUE_TITLE: ${{ github.event.issue.title }}
          ISSUE_BODY: ${{ github.event.issue.body }}
          ISSUE_LABELS: ${{ join(github.event.issue.labels.*.name, ', ') }}
        run: python .github/scripts/triage_analyze.py

      - name: Post analysis comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const analysis = fs.readFileSync('/tmp/analysis.md', 'utf8');
            const body = `## 🤖 Triage Agent\n\n${analysis}\n\n---\n_Automated analysis by NinjaStack Triage Agent. A maintainer will review and label accordingly._`;
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body
            });
