name: Security Audit

on:
  push:
    branches: [ main, develop, maintenance/* ]
  pull_request:
    branches: [ main ]
  schedule:
    # Run security scan daily at 2 AM UTC
    - cron: '0 2 * * *'

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.12'

    - name: Cache dependencies
      uses: actions/cache@v3
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
        restore-keys: |
          ${{ runner.os }}-pip-

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

    - name: Run dependency vulnerability scan
      run: |
        echo "::group::pip-audit scan"
        pip-audit --desc --output json --output-file security-report-pip-audit.json || true
        pip-audit --desc
        echo "::endgroup::"

    - name: Run safety check
      run: |
        echo "::group::safety scan"
        safety check --output json --output-file security-report-safety.json || true
        safety check
        echo "::endgroup::"

    - name: Run bandit security scan
      run: |
        echo "::group::bandit scan"
        bandit -r . -f json -o security-report-bandit.json || true
        bandit -r . -ll
        echo "::endgroup::"

    - name: Run secret detection scan
      run: |
        echo "::group::detect-secrets scan"
        detect-secrets scan --baseline .secrets.baseline
        echo "::endgroup::"

    - name: Upload security reports
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: security-reports
        path: security-report-*.json
        retention-days: 30

    - name: Security scan summary
      run: |
        echo "## Security Scan Summary" >> $GITHUB_STEP_SUMMARY
        echo "✅ Dependency vulnerability scan completed" >> $GITHUB_STEP_SUMMARY
        echo "✅ Secret detection scan completed" >> $GITHUB_STEP_SUMMARY
        echo "✅ Static security analysis completed" >> $GITHUB_STEP_SUMMARY
        echo "📊 Detailed reports available in artifacts" >> $GITHUB_STEP_SUMMARY

  secret-detection:
    name: Secret Detection
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0  # Fetch full history for secret detection

    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.12'

    - name: Install detect-secrets
      run: pip install detect-secrets

    - name: Run detect-secrets scan
      run: |
        detect-secrets scan --baseline .secrets.baseline

    - name: Check for new secrets
      run: |
        detect-secrets audit .secrets.baseline
