name: Test Local GitHub Action Build

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:

jobs:
  test-action-local:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

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

    - name: Setup Bun
      uses: oven-sh/setup-bun@v1
      with:
        bun-version: latest

    - name: Install system dependencies for skia-canvas
      run: |
        sudo apt-get update
        sudo apt-get install -y \
          build-essential \
          libcairo2-dev \
          libpango1.0-dev \
          libjpeg-dev \
          libgif-dev \
          librsvg2-dev \
          libpixman-1-dev \
          pkg-config \
          python3 \
          make \
          g++ \
          libstdc++6

    - name: Install dependencies
      run: bun install

    - name: Rebuild native modules
      env:
        NODE_ENV: production
        SKIA_CANVAS_USE_SYSTEM_LIBRARIES: 1
      run: |
        # Rebuild skia-canvas native modules
        cd node_modules/skia-canvas && npm rebuild
        cd ../..
        # Debug: Check what's in the skia-canvas directory
        ls -la node_modules/skia-canvas/lib/
        # Verify the module can be loaded
        node -e "console.log('Testing skia-canvas import...'); require('skia-canvas'); console.log('✅ skia-canvas loaded successfully')"

    - name: Build action
      run: bun run build

    - name: Run local action against test packages (updates Test-Readme.md)
      id: run-action
      uses: ./
      with:
        npm-packages: 'sailpoint-api-client'
        github-repositories: 'sailpoint-oss/sailpoint-cli'
        pypi-packages: 'sailpoint'
        powershell-modules: 'PSSailPoint,PSSailpoint.V3,PSSailpoint.Beta,PSSailpoint.V2024,PSSailpoint.V2025'
        json-output-path: 'stats.json'
        update-readme: 'true'
        readme-path: 'Test-Readme.md'
        github-token: ${{ secrets.GITHUB_TOKEN }}

    - name: Check generated outputs
      run: |
        echo "=== Checking Generated Outputs ==="
        ls -la stats.json Test-Readme.md
        echo "--- stats.json (first 40 lines) ---"
        head -40 stats.json | sed 's/.*/    &/'
        echo "--- Test-Readme.md (first 60 lines) ---"
        head -60 Test-Readme.md | sed 's/.*/    &/'
        echo "--- Validate README markers updated ---"
        if grep -q "<!-- METRICS_START -->" Test-Readme.md && grep -q "<!-- METRICS_END -->" Test-Readme.md; then
          echo "✅ README markers present"
        else
          echo "❌ README markers missing" && exit 1
        fi

    - name: Validate JSON structure (basic)
      run: |
        echo "=== Validating stats.json ==="
        test -f stats.json || (echo "❌ stats.json not found" && exit 1)
        jq -e 'type == "array" and length >= 1' stats.json > /dev/null || (echo "❌ stats.json not in expected format" && exit 1)