name: SBOM Generation & License Compliance

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]
  release:
    types: [published]

jobs:
  sbom-compliance:
    name: Generate SBOM & Check License Compliance
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Set up Rust
        uses: actions-rust-lang/setup-rust-toolchain@1780873c7b576612439a134613cc4cc74ce5538c # v1.15.2
        with:
          toolchain: stable

      - name: Install cargo-cyclonedx
        run: cargo install cargo-cyclonedx

      - name: Set up Python
        uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
        with:
          python-version: '3.11'

      - name: Install scancode-toolkit
        run: |
          python3 -m venv venv
          venv/bin/pip install --upgrade pip
          venv/bin/pip install scancode-toolkit

      - name: Install CycloneDX CLI
        run: |
          mkdir -p ~/.local/bin
          wget -q -O ~/.local/bin/cyclonedx \
            https://github.com/CycloneDX/cyclonedx-cli/releases/download/v0.27.1/cyclonedx-linux-x64
          chmod +x ~/.local/bin/cyclonedx
          echo "$HOME/.local/bin" >> $GITHUB_PATH

      - name: Generate Complete SBOM
        run: .github/scripts/generate_sbom.sh

      - name: Validate SBOM Format
        run: cyclonedx validate --input-file sbom.json

      - name: Upload SBOM Artifacts
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
        with:
          name: sbom-${{ github.sha }}
          path: |
            sbom.json
            NOTICE
          retention-days: 90

      - name: Fail on License Violations
        if: failure()
        run: |
          echo "❌ SBOM generation or license policy check failed!"
          echo "Review the output above for details."
          exit 1

  release-sbom:
    name: Attach SBOM to Release
    if: github.event_name == 'release'
    runs-on: ubuntu-latest
    needs: sbom-compliance

    steps:
      - name: Download SBOM Artifacts
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
        with:
          name: sbom-${{ github.sha }}

      - name: Attach SBOM to Release
        uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0
        with:
          files: |
            sbom.json
            NOTICE
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
