name: Table Format Check

on:
  workflow_call:
    inputs:
      soft-fail:
        description: 'Whether to continue on table format issues'
        required: false
        type: boolean
        default: false

# Minimal permissions
permissions:
  contents: read

jobs:
  table-format:
    name: Table Format Check
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4.2.2
        with:
          persist-credentials: false

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

      - name: Install dependencies
        run: npm ci

      - name: Check table formatting
        id: table-format
        run: |
          set +e
          npm run format:tables > table-format-output.txt 2>&1
          FORMAT_EXIT_CODE=$?
          set -e
          cat table-format-output.txt
          if [ "$FORMAT_EXIT_CODE" -ne 0 ] || [ -n "$(git diff --name-only)" ]; then
            echo "TABLE_FORMAT_FAILED=true" >> "$GITHUB_ENV"
            if [ -n "$(git diff --name-only)" ]; then
              echo "Files with formatting issues:"
              git diff --name-only
            fi
          fi
        continue-on-error: true

      - name: Create annotations
        if: env.TABLE_FORMAT_FAILED == 'true'
        run: |
          echo "::warning::Table formatting issues found. This check does NOT auto-fix. Please manually format tables or run 'npm run format:tables' locally."

      - name: Upload table format results
        if: always()
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v4.4.3
        with:
          name: table-format-results
          path: table-format-output.txt
          retention-days: 30

      - name: Add job summary
        if: always()
        run: |
          {
            echo "## Table Format Check Results"
            if [ "${{ env.TABLE_FORMAT_FAILED }}" == "true" ]; then
              echo "❌ **Status**: Failed"
              echo ""
              echo "⚠️ **Note**: This check does NOT auto-fix tables."
              echo ""
              echo "**To fix manually:**"
              echo "1. Run \`npm run format:tables\` locally"
              echo "2. Review and commit the changes"
              echo "3. Push to update this PR"
            else
              echo "✅ **Status**: Passed"
              echo ""
              echo "All tables are properly formatted."
            fi
          } >> "$GITHUB_STEP_SUMMARY"

      - name: Fail job if issues found
        if: env.TABLE_FORMAT_FAILED == 'true' && !inputs.soft-fail
        run: |
          echo "Table format check failed"
          exit 1
