name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  validate:
    name: Validate Files
    runs-on: ubuntu-latest

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

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

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Lint (ESLint)
        run: npm run lint
        continue-on-error: true

      - name: Lint CSS selectors (host-page leak audit)
        run: npm run lint:css

      - name: Build
        run: npm run build

      - name: Check committed dist is in sync with src (drift gate)
        run: |
          git diff --exit-code -- dist || {
            echo "ERROR: committed dist/ is out of sync with src/. Run 'npm run build' and commit dist/.";
            exit 1;
          }
          echo "dist/ is in sync with src/ - OK"

      - name: Check standalone bundle size cap (500KB)
        run: |
          SIZE=$(stat -c%s dist/webAccTools.standalone.min.js)
          echo "standalone bundle size: $SIZE bytes"
          if [ "$SIZE" -gt 512000 ]; then
            echo "ERROR: standalone bundle exceeds 500KB cap - inlined assets grew too large."
            exit 1
          fi

      - name: Security audit (high severity)
        run: npm audit --audit-level=high
        continue-on-error: true

      - name: Validate config.example.json is valid JSON
        run: node -e "JSON.parse(require('fs').readFileSync('config.example.json','utf8')); console.log('config.example.json OK')"

      - name: Validate dist/webAccTools.js syntax
        run: node --check dist/webAccTools.js && echo "webAccTools.js syntax OK"

      - name: Check dist/watInit.js syntax
        run: node --check dist/watInit.js && echo "watInit.js syntax OK"

      - name: Check for sensitive data (config.json should not exist in repo)
        run: |
          if [ -f "config.json" ]; then
            echo "ERROR: config.json should not be committed (it is in .gitignore)"
            exit 1
          fi
          echo "config.json not present in repo - OK"

      - name: Verify required release files exist
        run: |
          for f in "dist/webAccTools.js" "dist/webAccTools.standalone.min.js" "dist/assets/css/webAccTools.css" "config.example.json" "README.md" "CHANGELOG.md" "LICENSE" "CONTRIBUTING.md"; do
            if [ ! -f "$f" ]; then
              echo "ERROR: Required file missing: $f"
              exit 1
            fi
          done
          echo "All required files present - OK"
