name: Security Scanning

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]
  schedule:
    # Run weekly on Mondays at 00:00 UTC
    - cron: '0 0 * * 1'

jobs:
  security-scan:
    name: Security Vulnerability Scan
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.10'
        
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install bandit safety detect-secrets
        cd backend && pip install -r requirements.txt
        
    - name: Run Bandit (Python Security Linter)
      run: |
        bandit -r backend/app -f json -o bandit-report.json || true
        bandit -r backend/app
      continue-on-error: true
      
    - name: Run Safety (Dependency Vulnerability Check)
      run: |
        safety check --json || true
        safety check
      continue-on-error: true
      
    - name: Run detect-secrets
      run: |
        detect-secrets scan --baseline .secrets.baseline || true
      continue-on-error: true
      
    - name: Upload Bandit Report
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: bandit-security-report
        path: bandit-report.json
        
  codeql-analysis:
    name: CodeQL Analysis
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write
      
    strategy:
      fail-fast: false
      matrix:
        language: [ 'python' ]
        
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v2
      with:
        languages: ${{ matrix.language }}
        queries: security-and-quality
        
    - name: Autobuild
      uses: github/codeql-action/autobuild@v2
      
    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v2
      with:
        category: "/language:${{matrix.language}}"
        
  dependency-review:
    name: Dependency Review
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      
    - name: Dependency Review
      uses: actions/dependency-review-action@v3
      with:
        fail-on-severity: moderate
