name: Update Abacus React Examples

on:
  push:
    branches: [main]
    paths:
      - "packages/abacus-react/src/**/*"
      - "packages/abacus-react/generate-examples.js"
      - "packages/abacus-react/package.json"
  workflow_dispatch: # Allow manual triggering
  schedule:
    # Run weekly on Sundays at 3 AM UTC to keep examples fresh
    - cron: "0 3 * * 0"

# Grant write permissions to push changes back to repository
permissions:
  contents: write
  pull-requests: write

jobs:
  update-examples:
    name: Regenerate AbacusReact Examples
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          fetch-depth: 0 # Fetch full history for proper commits

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: latest

      - name: Install dependencies
        run: pnpm install

      - name: Build AbacusReact package
        working-directory: packages/abacus-react
        run: |
          echo "🔨 Building AbacusReact package..."
          pnpm run build

          echo "✅ Build completed successfully"
          ls -la dist/ || echo "No dist directory found"

      - name: Generate fresh examples and documentation
        working-directory: packages/abacus-react
        run: |
          echo "🎨 Generating fresh AbacusReact examples and documentation..."

          pnpm run generate-examples

          echo "✅ Example generation completed"

          # List generated files
          echo "📂 Generated/updated files:"
          ls -la src/AbacusReact.examples.stories.tsx 2>/dev/null || echo "No examples stories found"
          ls -la README.md 2>/dev/null || echo "No README found"

      - name: Check for changes
        id: changes
        run: |
          # Add all relevant files to staging to check for changes
          git add packages/abacus-react/src/AbacusReact.examples.stories.tsx 2>/dev/null || true
          git add packages/abacus-react/README.md 2>/dev/null || true

          # Check if there are any staged changes
          if git diff --cached --quiet; then
            echo "changed=false" >> $GITHUB_OUTPUT
            echo "📄 No changes detected in examples or documentation"
          else
            echo "changed=true" >> $GITHUB_OUTPUT
            echo "📄 Changes detected in examples and documentation:"
            git diff --cached --name-only
            echo ""
            echo "🔍 Detailed changes:"
            git diff --cached --stat
          fi

      - name: Commit updated examples
        if: steps.changes.outputs.changed == 'true'
        run: |
          # Configure git with proper user info
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"

          # The files are already staged from the previous step
          git commit -m "📚 Update AbacusReact examples and documentation

          Auto-generated fresh examples and balanced documentation from latest component changes.
          Includes comprehensive usage patterns, API documentation, and educational examples.

          Files updated:
          $(git diff --cached --name-only | sed 's/^/- /')

          🤖 Generated with GitHub Actions

          Co-Authored-By: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>"

      - name: Push changes
        if: steps.changes.outputs.changed == 'true'
        run: |
          # Push changes using git directly for better control
          echo "🚀 Pushing updated examples to main branch..."
          git push origin main
          echo "✅ Successfully pushed changes to main branch"

      - name: Create summary
        run: |
          echo "## 📚 AbacusReact Examples Update Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

          if [ "${{ steps.changes.outputs.changed }}" == "true" ]; then
            echo "✅ **Examples and documentation updated successfully**" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "The following files were regenerated:" >> $GITHUB_STEP_SUMMARY
            echo "### 📖 Documentation:" >> $GITHUB_STEP_SUMMARY
            echo "- **README.md** - Balanced documentation with core features, API reference, and educational examples" >> $GITHUB_STEP_SUMMARY
            echo "- **AbacusReact.examples.stories.tsx** - Comprehensive Storybook examples demonstrating key features" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "### 🎯 Key Features Documented:" >> $GITHUB_STEP_SUMMARY
            echo "- **Basic Usage** - Simple abacus display and configuration" >> $GITHUB_STEP_SUMMARY
            echo "- **Interactive Mode** - Click handling and animations" >> $GITHUB_STEP_SUMMARY
            echo "- **Custom Styling** - Granular appearance control and theming" >> $GITHUB_STEP_SUMMARY
            echo "- **Tutorial System** - Educational overlays and guidance" >> $GITHUB_STEP_SUMMARY
            echo "- **Advanced Features** - Bead references, callbacks, and hooks" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "### 🔧 Documentation Features:" >> $GITHUB_STEP_SUMMARY
            echo "- **Balanced coverage** - Equal focus on all component capabilities" >> $GITHUB_STEP_SUMMARY
            echo "- **TypeScript support** - Complete interface documentation" >> $GITHUB_STEP_SUMMARY
            echo "- **Educational examples** - Real-world usage patterns for math education" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "Changes have been committed and pushed to the main branch." >> $GITHUB_STEP_SUMMARY
          else
            echo "ℹ️ **No updates needed**" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "Examples and documentation are already up-to-date with the latest component changes." >> $GITHUB_STEP_SUMMARY
          fi

          echo "" >> $GITHUB_STEP_SUMMARY
          echo "_This action runs automatically when AbacusReact source code is modified, and weekly to ensure freshness._" >> $GITHUB_STEP_SUMMARY

  validate-examples:
    name: Validate Generated Examples
    runs-on: ubuntu-latest
    needs: update-examples
    if: always() # Run even if update-examples fails

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: latest

      - name: Install dependencies
        run: pnpm install

      - name: Validate examples exist and are accessible
        working-directory: packages/abacus-react
        run: |
          echo "🔍 Validating example files..."

          # Check that all expected files exist
          expected_files=(
            "src/AbacusReact.examples.stories.tsx"
            "README.md"
            "generate-examples.js"
          )

          missing_files=()
          for file in "${expected_files[@]}"; do
            if [ ! -f "$file" ]; then
              missing_files+=("$file")
              echo "❌ Missing: $file"
            else
              # Check file size (should be > 1KB for valid content)
              size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null || echo "0")
              if [ "$size" -gt 1000 ]; then
                echo "✅ Valid: $file (${size} bytes)"
              else
                echo "⚠️  Suspicious: $file (${size} bytes - too small?)"
              fi
            fi
          done

          if [ ${#missing_files[@]} -gt 0 ]; then
            echo "❌ Validation failed: ${#missing_files[@]} files missing"
            exit 1
          else
            echo "✅ All example files validated successfully"
          fi

      - name: Test AbacusReact package integration
        run: |
          # Quick test that the AbacusReact package still works
          cd packages/abacus-react

          # Build the package to ensure TypeScript compilation works
          pnpm run build

          # Verify the built package has expected exports
          node -e "
            const pkg = require('./package.json');
            console.log('✅ Package loaded successfully');
            console.log('📦 Package name:', pkg.name);
            console.log('📊 Version:', pkg.version);

            // Check that dist files exist
            const fs = require('fs');
            const expectedDist = ['dist/index.es.js', 'dist/index.cjs.js', 'dist/index.d.ts'];

            expectedDist.forEach(file => {
              if (fs.existsSync(file)) {
                console.log('✅', file, 'exists');
              } else {
                console.error('❌', file, 'not found');
                process.exit(1);
              }
            });
          "

      - name: Validate Storybook build
        working-directory: packages/abacus-react
        run: |
          echo "🔍 Validating Storybook configuration..."

          # Build Storybook to ensure examples stories work correctly
          pnpm run build-storybook

          echo "✅ Storybook built successfully"

          # Check that storybook-static directory was created
          if [ -d "storybook-static" ]; then
            echo "✅ Storybook static files generated"
            ls -la storybook-static/ | head -10
          else
            echo "❌ Storybook static files not found"
            exit 1
          fi
