# Claude Context Engineering - Context Budget Check
#
# This workflow monitors context budget and documentation health.
# Copy this file to .github/workflows/context-check.yml to enable.
#
# Runs on:
# - Push to main/master branches
# - Weekly schedule
# - Manual trigger

name: Context Budget Check

on:
  push:
    branches:
      - main
      - master
    paths:
      - '.ai-context/**'
  schedule:
    # Run weekly on Monday at 9am UTC
    - cron: '0 9 * * 1'
  workflow_dispatch:

jobs:
  context-health:
    name: Check Context Engineering Health
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          cache: 'npm'
          cache-dependency-path: '.ai-context/tools/package-lock.json'

      - name: Install CLI tools
        run: |
          cd .ai-context/tools
          npm ci

      - name: Run Full Diagnostics
        id: diagnose
        run: |
          echo "🔬 Running diagnostics..."
          npx .ai-context/tools/bin/claude-context.js diagnose --verbose > diagnostics.txt 2>&1
          cat diagnostics.txt
        continue-on-error: true

      - name: Calculate Documentation Metrics
        run: |
          echo "📊 Calculating metrics..."

          # Count workflow files
          WORKFLOW_COUNT=$(find .ai-context/context/workflows -name "*.md" 2>/dev/null | wc -l || echo "0")
          echo "Workflow files: $WORKFLOW_COUNT"

          # Count agent files
          AGENT_COUNT=$(find .ai-context/agents -name "*.md" 2>/dev/null | wc -l || echo "0")
          echo "Agent files: $AGENT_COUNT"

          # Count command files
          COMMAND_COUNT=$(find .ai-context/commands -name "*.md" 2>/dev/null | wc -l || echo "0")
          echo "Command files: $COMMAND_COUNT"

          # Estimate total documentation tokens (rough: 1 token ≈ 4 chars)
          TOTAL_CHARS=$(find .claude -name "*.md" -exec cat {} \; 2>/dev/null | wc -c || echo "0")
          ESTIMATED_TOKENS=$((TOTAL_CHARS / 4))
          echo "Estimated documentation tokens: $ESTIMATED_TOKENS"

          # Calculate as percentage of budget
          MAX_TOKENS=200000
          PERCENTAGE=$((ESTIMATED_TOKENS * 100 / MAX_TOKENS))
          echo "Context budget usage: ${PERCENTAGE}%"

          # Save metrics
          cat > metrics.json << EOF
          {
            "workflow_count": $WORKFLOW_COUNT,
            "agent_count": $AGENT_COUNT,
            "command_count": $COMMAND_COUNT,
            "estimated_tokens": $ESTIMATED_TOKENS,
            "budget_percentage": $PERCENTAGE,
            "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
          }
          EOF

          cat metrics.json

      - name: Check Budget Threshold
        run: |
          PERCENTAGE=$(jq '.budget_percentage' metrics.json)
          echo "Current usage: ${PERCENTAGE}%"

          if [ "$PERCENTAGE" -gt 60 ]; then
            echo "⚠️ WARNING: Documentation exceeds 60% of context budget!"
            echo "Consider compacting or splitting documentation."
            exit 1
          elif [ "$PERCENTAGE" -gt 40 ]; then
            echo "📊 Documentation is at ${PERCENTAGE}% - approaching target limit"
          else
            echo "✅ Documentation is within healthy range (${PERCENTAGE}%)"
          fi

      - name: Run Validation Suite
        run: |
          echo "🔍 Running validation..."
          npx .ai-context/tools/bin/claude-context.js validate --all > validation.txt 2>&1 || true
          cat validation.txt

      - name: Upload Metrics
        uses: actions/upload-artifact@v4
        with:
          name: context-metrics
          path: |
            metrics.json
            diagnostics.txt
            validation.txt
          retention-days: 30

      - name: Create Issue on Failure
        if: failure() && github.event_name == 'schedule'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            let metrics = {};
            try {
              metrics = JSON.parse(fs.readFileSync('metrics.json', 'utf8'));
            } catch (e) {
              metrics = { error: 'Could not read metrics' };
            }

            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: '⚠️ Claude Context Engineering Health Check Failed',
              body: `## Weekly Health Check Failed\n\n**Metrics:**\n\`\`\`json\n${JSON.stringify(metrics, null, 2)}\n\`\`\`\n\n**Action Required:**\n- Review documentation health\n- Run \`npx claude-context diagnose\` locally\n- Consider documentation compaction if over budget\n\n---\n*Generated by Claude Context Engineering CI*`,
              labels: ['documentation', 'maintenance']
            });
