name: Full Codebase Security Scan
on:
  workflow_dispatch:
    inputs:
      max_files:
        description: 'Maximum number of files to scan (cost control)'
        required: false
        default: '50'
      extensions:
        description: 'File extensions (comma-separated)'
        required: false
        default: 'c,cpp,cc,cxx,h,hpp'

jobs:
  security-scan:
    runs-on: ubuntu-latest
    if: github.server_url == 'https://github.com'
    steps:
      - uses: actions/checkout@v4

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

      - name: Install Claude SDK
        run: pip install anthropic

      - name: Run Security Analysis
        env:
          ANTHROPIC_API_KEY: ${{ secrets.CLAUDE_API_KEY }}
          MAX_FILES: ${{ github.event.inputs.max_files || '50' }}
          EXTENSIONS: ${{ github.event.inputs.extensions || 'c,cpp,cc,cxx,h,hpp' }}
        run: |
          python3 << 'EOF'
          import anthropic
          import os
          import glob
          import json
          from datetime import datetime

          def get_code_files(extensions, max_files):
              """Find code files to analyze"""
              code_files = []
              exclude_dirs = {'.git', 'node_modules', '__pycache__', 'venv', 'build', 'dist', 'target'}

              for ext in extensions.split(','):
                  ext = ext.strip()
                  files = glob.glob(f"**/*.{ext}", recursive=True)

                  # Filter out excluded directories
                  for file in files:
                      if not any(excluded in file for excluded in exclude_dirs):
                          code_files.append(file)

              # Remove duplicates, sort, and limit
              code_files = sorted(list(set(code_files)))[:int(max_files)]
              return code_files

          def analyze_file(client, file_path):
              """Analyze a single file for security issues"""
              try:
                  # Read file with size limit for cost control
                  with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                      content = f.read()[:6000]  # Limit to ~6k chars per file

                  prompt = f"""Analyze this {file_path} file for security vulnerabilities in a C/C++ Linux terminal music player application.

          CONTEXT: This is a terminal music player with NO database, web access, or network functionality. Focus on vulnerabilities specific to:

          CRITICAL AUDIO FILE PARSING VULNERABILITIES:
          1. Buffer overflows when parsing music file headers (MP3, FLAC, OGG, WAV, etc.)
          2. Integer overflows in size calculations for audio data
          3. Heap corruption from malformed audio metadata
          4. Stack buffer overflows in filename/path handling
          5. Format string vulnerabilities in audio tag parsing
          6. Unsafe memory operations when reading variable-length audio data

          GENERAL C/C++ SECURITY ISSUES:
          7. Buffer overflows (strcpy, strcat, gets, scanf, etc.)
          8. Use-after-free and double-free vulnerabilities
          9. Null pointer dereferences
          10. Integer overflows in memory allocations
          11. Unsafe pointer arithmetic
          12. Missing bounds checking on arrays
          13. Race conditions in file I/O
          14. Path traversal in file operations
          15. Memory leaks that could lead to DoS

          AUDIO-SPECIFIC ATTACK VECTORS:
          16. Malicious embedded album art (large images causing memory exhaustion)
          17. Crafted playlists with overly long file paths
          18. Audio files with corrupted or oversized metadata tags
          19. Files with misleading file extensions vs actual format
          20. Symbolic link attacks in music directory traversal

          Rate severity as: CRITICAL, HIGH, MEDIUM, LOW
          Pay special attention to any code that processes untrusted audio file data.

          Code:
          ```
          {content}
          ```

          Respond with findings in this format:
          SEVERITY: Description (function name) - AUDIO_PARSING/BUFFER/MEMORY/etc
          """

                  response = client.messages.create(
                      model="claude-sonnet-4-20250514",
                      max_tokens=1500,
                      messages=[{"role": "user", "content": prompt}]
                  )

                  return response.content[0].text

              except Exception as e:
                  return f"Error analyzing {file_path}: {str(e)}"

          def main():
              # Setup
              api_key = os.environ.get('ANTHROPIC_API_KEY')
              if not api_key:
                  print("❌ ERROR: ANTHROPIC_API_KEY not found")
                  return

              max_files = os.environ.get('MAX_FILES', '50')
              extensions = os.environ.get('EXTENSIONS', 'c,cpp,h')

              print(f"🔍 Security Scan Starting")
              print(f"📁 Max files: {max_files}")
              print(f"📄 Extensions: {extensions}")
              print("=" * 60)

              client = anthropic.Anthropic(api_key=api_key)

              # Find files
              code_files = get_code_files(extensions, max_files)
              print(f"Found {len(code_files)} files to analyze\n")

              # Analyze files
              total_issues = 0
              critical_issues = 0

              for i, file_path in enumerate(code_files, 1):
                  print(f"[{i:2d}/{len(code_files)}] 🔍 {file_path}")

                  analysis = analyze_file(client, file_path)

                  # Count issues
                  if "CRITICAL:" in analysis:
                      critical_issues += analysis.count("CRITICAL:")
                      total_issues += analysis.count("CRITICAL:")
                  if "HIGH:" in analysis:
                      total_issues += analysis.count("HIGH:")
                  if "MEDIUM:" in analysis:
                      total_issues += analysis.count("MEDIUM:")
                  if "LOW:" in analysis:
                      total_issues += analysis.count("LOW:")

                  # Print results
                  if any(severity in analysis for severity in ["CRITICAL:", "HIGH:", "MEDIUM:", "LOW:"]):
                      print(f"     ⚠️  Issues found:")
                      for line in analysis.split('\n'):
                          if any(severity in line for severity in ["CRITICAL:", "HIGH:", "MEDIUM:", "LOW:"]):
                              print(f"     {line}")
                      print()
                  else:
                      print("     ✅ No issues found")

                  print("-" * 50)

              # Summary
              print(f"\n🎯 SECURITY SCAN COMPLETE")
              print(f"📊 Files analyzed: {len(code_files)}")
              print(f"⚠️  Total issues: {total_issues}")
              print(f"🚨 Critical issues: {critical_issues}")
              print(f"💰 Estimated cost: ~${len(code_files) * 0.15:.2f}")

              if critical_issues > 0:
                  print("\n🚨 CRITICAL ISSUES FOUND - Review immediately!")
              elif total_issues > 0:
                  print(f"\n⚠️  {total_issues} security issues found - Review recommended")
              else:
                  print("\n✅ No security issues detected")

          if __name__ == "__main__":
              main()
          EOF

      - name: Upload Results Summary
        if: always()
        run: |
          echo "Security scan completed at $(date)" > scan-summary.txt
          echo "Check the logs above for detailed findings" >> scan-summary.txt

      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: security-scan-summary
          path: scan-summary.txt
