name: Dependency Audit

on:
  pull_request:
    branches: [main]
    paths:
      - 'requirements.txt'
      - 'pyproject.toml'
      - 'uv.lock'
  schedule:
    - cron: '0 8 * * 1'  # Weekly on Monday
  workflow_dispatch:

permissions:
  pull-requests: write
  contents: read

jobs:
  audit:
    name: Audit Python dependencies
    runs-on: ubuntu-latest
    container: catthehacker/ubuntu:act-22.04
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - name: Set up Python
        run: uv python install 3.11
      - name: Install pip-audit
        run: uv pip install --system pip-audit
      - name: Run pip-audit
        id: audit
        run: |
          set -euo pipefail
          # Run pip-audit against the lock file/requirements
          if pip-audit --requirement requirements.txt -f json -o /tmp/audit-results.json 2>/tmp/audit-stderr.txt; then
            echo "found=false" >> "$GITHUB_OUTPUT"
          else
            echo "found=true" >> "$GITHUB_OUTPUT"
            # Check severity
            CRITICAL=$(python3 -c "
          import json, sys
          data = json.load(open('/tmp/audit-results.json'))
          vulns = data.get('dependencies', [])
          for d in vulns:
              for v in d.get('vulns', []):
                  aliases = v.get('aliases', [])
                  # Check for critical/high CVSS
                  if any('CVSS' in str(a) for a in aliases):
                      print('true')
                      sys.exit(0)
          print('false')
          " 2>/dev/null || echo 'false')
            echo "critical=${CRITICAL}" >> "$GITHUB_OUTPUT"
          fi
        continue-on-error: true
      - name: Post results comment
        if: steps.audit.outputs.found == 'true' && github.event_name == 'pull_request'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          BODY="## ⚠️ Dependency Vulnerabilities Detected

          \`pip-audit\` found vulnerable dependencies in this PR. Review and update before merging.

          \`\`\`
          $(cat /tmp/audit-results.json | python3 -c "
          import json, sys
          data = json.load(sys.stdin)
          for dep in data.get('dependencies', []):
              for v in dep.get('vulns', []):
                  print(f\"  {dep['name']}=={dep['version']}: {v['id']} - {v.get('description', '')[:120]}\")
          " 2>/dev/null || cat /tmp/audit-stderr.txt)
          \`\`\`

          ---
          *Automated scan by [dependency-audit](/.github/workflows/dependency-audit.yml)*"
          gh pr comment "${{ github.event.pull_request.number }}" --body "$BODY"
      - name: Fail on vulnerabilities
        if: steps.audit.outputs.found == 'true'
        run: |
          echo "::error::Vulnerable dependencies detected. See PR comment for details."
          cat /tmp/audit-results.json | python3 -m json.tool || true
          exit 1
