name: Code Size Limits

on:
  pull_request:
    paths:
      - 'frontends/nextjs/src/**/*.{ts,tsx,js,jsx}'
      - 'tools/enforce-size-limits.ts'
      - '.github/workflows/size-limits.yml'
  push:
    branches:
      - main
    paths:
      - 'frontends/nextjs/src/**/*.{ts,tsx,js,jsx}'

jobs:
  size-limits:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: frontends/nextjs
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: '1.3.4'

      - name: Cache Bun dependencies
        uses: actions/cache@v4
        with:
          key: bun-deps-${{ runner.os }}-${{ hashFiles('bun.lock') }}
          path: |
            frontends/nextjs/node_modules
            ~/.bun
          restore-keys: bun-deps-${{ runner.os }}-
      
      - name: Install dependencies
        run: bun install --frozen-lockfile
      
      - name: Check code size limits
        run: bunx tsx ../../tools/enforce-size-limits.ts
      
      - name: Upload report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: size-limits-report
          path: frontends/nextjs/size-limits-report.json
          retention-days: 7
      
      - name: Comment on PR
        if: failure() && github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const report = JSON.parse(fs.readFileSync('frontends/nextjs/size-limits-report.json', 'utf8'));
            
            let comment = '## 📏 Code Size Limits\n\n';
            
            if (report.errors === 0 && report.warnings === 0) {
              comment += '✅ All files pass size limits!';
            } else {
              if (report.errors > 0) {
                comment += `### ❌ Errors (${report.errors})\n`;
                report.violations
                  .filter(v => v.severity === 'error')
                  .forEach(v => {
                    comment += `- **${v.file}**: ${v.metric} (${v.current} / ${v.limit})\n`;
                  });
              }
              
              if (report.warnings > 0) {
                comment += `\n### ⚠️ Warnings (${report.warnings})\n`;
                report.violations
                  .filter(v => v.severity === 'warning')
                  .forEach(v => {
                    comment += `- **${v.file}**: ${v.metric} (${v.current} / ${v.limit})\n`;
                  });
              }
              
              comment += '\n[See refactoring guide →](../blob/main/docs/REFACTORING_ENFORCEMENT_GUIDE.md)';
            }
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });
