name: License Compliance Checker

on:
  push:
    branches: [main, develop]
    paths:
      - '**/package.json'
      - '**/package-lock.json'
      - '**/yarn.lock'
      - '**/pnpm-lock.yaml'
      - '**/requirements*.txt'
      - '**/pyproject.toml'
      - '**/Pipfile.lock'
      - '**/go.sum'
  pull_request:
    branches: [main, develop]
  schedule:
    - cron: '0 9 * * 1'   # every Monday at 09:00 UTC
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: write

# --- Configure allowed / denied licenses below ---
env:
  ALLOWED_LICENSES: >-
    MIT;
    Apache-2.0;
    BSD-2-Clause;
    BSD-3-Clause;
    ISC;
    0BSD;
    CC0-1.0;
    Unlicense;
    Python-2.0
  DENIED_LICENSES: >-
    GPL-2.0;
    GPL-3.0;
    LGPL-2.0;
    LGPL-2.1;
    LGPL-3.0;
    AGPL-3.0;
    SSPL-1.0;
    Commons-Clause

jobs:
  node-license-check:
    name: Node.js — license-checker
    runs-on: ubuntu-latest
    if: hashFiles('**/package-lock.json') != ''
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Install license-checker
        run: npm install -g license-checker

      - name: Check licenses
        run: |
          license-checker \
            --json \
            --out license-report-node.json \
            --excludePrivatePackages

          # Fail on denied licenses
          DENIED=$(echo "$DENIED_LICENSES" | tr ';' '\n' | tr -d ' ')
          for license in $DENIED; do
            if grep -q "\"$license\"" license-report-node.json; then
              echo "::error::Denied license found: $license"
              exit 1
            fi
          done

      - name: Upload license report
        uses: actions/upload-artifact@v4
        with:
          name: license-report-node
          path: license-report-node.json

  python-license-check:
    name: Python — pip-licenses
    runs-on: ubuntu-latest
    if: hashFiles('**/requirements*.txt') != ''
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
          cache: pip

      - name: Install dependencies
        run: |
          pip install -r requirements.txt
          pip install pip-licenses

      - name: Generate license report
        run: |
          pip-licenses \
            --format=json \
            --output-file=license-report-python.json \
            --with-urls \
            --with-description

      - name: Check for denied licenses
        run: |
          python - <<'EOF'
          import json, os, sys

          with open("license-report-python.json") as f:
              packages = json.load(f)

          denied = [l.strip() for l in os.environ.get("DENIED_LICENSES", "").split(";") if l.strip()]
          violations = []

          for pkg in packages:
              lic = pkg.get("License", "UNKNOWN")
              for d in denied:
                  if d.lower() in lic.lower():
                      violations.append(f"{pkg['Name']} ({lic})")

          if violations:
              print("::error::Denied licenses found:")
              for v in violations:
                  print(f"  - {v}")
              sys.exit(1)
          else:
              print(f"All {len(packages)} packages have compliant licenses.")
          EOF

      - name: Upload license report
        uses: actions/upload-artifact@v4
        with:
          name: license-report-python
          path: license-report-python.json

  fossa:
    name: FOSSA — policy scan
    runs-on: ubuntu-latest
    if: vars.ENABLE_FOSSA == 'true'
    steps:
      - uses: actions/checkout@v4

      - name: Run FOSSA analysis
        uses: fossas/fossa-action@main
        with:
          api-key: ${{ secrets.FOSSA_API_KEY }}

  summary:
    name: License Compliance Summary
    runs-on: ubuntu-latest
    needs: [node-license-check, python-license-check]
    if: always()
    steps:
      - name: Download reports
        uses: actions/download-artifact@v4

      - name: Write job summary
        run: |
          echo "## License Compliance Results" >> $GITHUB_STEP_SUMMARY
          echo "| Ecosystem | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|-----------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Node.js   | ${{ needs.node-license-check.result }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Python    | ${{ needs.python-license-check.result }} |" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### Denied License Categories" >> $GITHUB_STEP_SUMMARY
          echo "\`${{ env.DENIED_LICENSES }}\`" >> $GITHUB_STEP_SUMMARY
