name: Planning Agent

on:
  issues:
    types: [labeled]

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

      - name: Gather context
        env:
          ISSUE_TITLE: ${{ github.event.issue.title }}
          ISSUE_BODY: ${{ github.event.issue.body }}
        run: |
          find libs apps -type f -name "*.py" | head -200 > /tmp/repo_files.txt
          echo "" > /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 -3)
            for f in $matches; do
              echo "" >> /tmp/relevant_code.md
              echo "### $f" >> /tmp/relevant_code.md
              cat "$f" >> /tmp/relevant_code.md
            done
          done
          head -c 40000 /tmp/relevant_code.md > /tmp/rc_trimmed.md
          mv /tmp/rc_trimmed.md /tmp/relevant_code.md
          echo "" > /tmp/triage_comment.txt

      - name: Fetch triage analysis comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const comments = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number
            });
            const triageComment = comments.data.find(c => c.body.includes('Triage Agent'));
            if (triageComment) {
              fs.writeFileSync('/tmp/triage_comment.txt', triageComment.body);
            }

      - name: Generate plan with GPT 5.2
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          ISSUE_TITLE: ${{ github.event.issue.title }}
          ISSUE_BODY: ${{ github.event.issue.body }}
        run: python .github/scripts/planning_generate.py

      - name: Post plan comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync('/tmp/plan.md', 'utf8');
            const body = `## 🤖 Planning Agent\n\n${plan}\n\n---\n_React with 👍 to approve, or comment \`/approve\` to move to \`todo\`._`;
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body
            });
