name: Security Scan

on:
  pull_request:
    branches:
      - main
      - beta
      - dev

permissions:
  contents: read

jobs:
  security-checks:
    name: Security & Dependencies
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install bandit safety

      - name: Bandit security check
        run: |
          bandit -r src/ -f txt | tee bandit-report.txt
          
          # Extract HIGH severity (not confidence) - look for the severity section
          SEVERITY_SECTION=$(sed -n '/Total issues (by severity):/,/Total issues (by confidence):/p' bandit-report.txt)
          HIGH_COUNT=$(echo "$SEVERITY_SECTION" | grep "High:" | grep -o "[0-9]*" | head -1)
          
          if [ -z "$HIGH_COUNT" ]; then
            HIGH_COUNT=0
          fi
          
          if [ "$HIGH_COUNT" -gt 0 ]; then
            echo "Found $HIGH_COUNT HIGH severity security issues"
            exit 1
          fi
          echo "✓ No HIGH severity security issues found"

      - name: Safety check for dependencies
        run: safety check --json || true

      - name: Trivy vulnerability scan
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'fs'
          scan-ref: '.'
          format: 'table'
          severity: 'CRITICAL,HIGH'
          exit-code: '1'
