name: "🔒 Security Scan"

on:
  push:
    branches: [main, master, dev]
  pull_request:
    branches: [main, master]
  schedule:
    - cron: '0 0 * * 0'
  workflow_dispatch:

permissions:
  contents: read
  security-events: write
  actions: read

jobs:
  codeql:
    name: CodeQL Analysis
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: python

      - name: Autobuild
        uses: github/codeql-action/autobuild@v3

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3

  security-checks:
    name: Security Checks
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Check for secrets
        run: |
          echo "Scanning for potential secrets..."
          ! grep -rn 'AKIA\|sk-\|ghp_\|gho_\|password\s*=' --include='*.py' --include='*.js' --include='*.env' --include='*.yml' . || echo "Warning: Potential secrets found"
          echo "Security scan complete"

      - name: Check dependencies
        run: |
          if [ -f "requirements.txt" ]; then
            pip install safety 2>/dev/null || true
            safety check -r requirements.txt 2>/dev/null || true
          fi
          if [ -f "package.json" ]; then
            npm install 2>/dev/null || true
            npm audit --audit-level=high 2>/dev/null || true
          fi
          echo "Dependency check complete"

      - name: Dependency Review
        uses: actions/dependency-review-action@v4
        if: github.event_name == 'pull_request'
