#!/usr/bin/env python
"""
Git Security Check Script
Verifies that sensitive files are properly ignored by git.
"""

import subprocess
import os
from pathlib import Path

def run_git_command(command):
    """Run a git command and return the output"""
    try:
        result = subprocess.run(
            command.split(), 
            capture_output=True, 
            text=True, 
            cwd=Path(__file__).parent
        )
        return result.stdout.strip(), result.returncode
    except Exception as e:
        return str(e), 1

def check_env_file_status():
    """Check if .env file is properly ignored"""
    print("🔍 Git Security Check")
    print("=" * 40)
    
    # Check if .env file exists
    env_file = Path(__file__).parent / '.env'
    if env_file.exists():
        print("✅ .env file exists locally")
    else:
        print("❌ .env file not found")
        return False
    
    # Check if .env is in .gitignore
    gitignore_file = Path(__file__).parent / '.gitignore'
    if gitignore_file.exists():
        with open(gitignore_file, 'r') as f:
            gitignore_content = f.read()
            if '.env' in gitignore_content:
                print("✅ .env is in .gitignore")
            else:
                print("❌ .env not found in .gitignore")
                return False
    
    # Check if .env is tracked by git
    output, code = run_git_command("git ls-files .env")
    if code == 0 and output:
        print("❌ .env file is still tracked by git!")
        print(f"   Tracked file: {output}")
        return False
    else:
        print("✅ .env file is not tracked by git")
    
    # Check if .env is in git status (staged/modified)
    output, code = run_git_command("git status --porcelain")
    if code == 0:
        env_in_status = any('.env' in line and not line.endswith('.env.example') for line in output.split('\n'))
        if env_in_status:
            print("⚠️  .env file appears in git status (may be staged for deletion)")
            for line in output.split('\n'):
                if '.env' in line and not line.endswith('.env.example'):
                    print(f"   Status: {line}")
        else:
            print("✅ .env file not in git status")
    
    # Check if .env.example exists and is tracked
    output, code = run_git_command("git ls-files .env.example")
    if code == 0 and output:
        print("✅ .env.example is tracked (good for templates)")
    else:
        print("⚠️  .env.example not tracked (consider adding it)")
    
    return True

def check_sensitive_patterns():
    """Check for other sensitive patterns in git"""
    print("\n🔐 Sensitive Pattern Check")
    print("=" * 40)
    
    # Check for potential secrets in tracked files
    sensitive_patterns = [
        "password",
        "secret",
        "api_key",
        "private_key",
        "token"
    ]
    
    for pattern in sensitive_patterns:
        output, code = run_git_command(f"git grep -i {pattern}")
        if code == 0 and output:
            lines = output.split('\n')
            # Filter out comments and safe patterns
            suspicious_lines = [
                line for line in lines 
                if not line.strip().startswith('#') 
                and 'password_validation' not in line.lower()
                and 'secret_key' not in line.lower() or 'os.getenv' in line
            ]
            if suspicious_lines:
                print(f"⚠️  Found potential {pattern} in tracked files:")
                for line in suspicious_lines[:3]:  # Show first 3 matches
                    print(f"   {line}")
                if len(suspicious_lines) > 3:
                    print(f"   ... and {len(suspicious_lines) - 3} more")
    
    print("✅ Sensitive pattern check complete")

def main():
    """Main security check function"""
    env_secure = check_env_file_status()
    check_sensitive_patterns()
    
    print("\n" + "=" * 40)
    if env_secure:
        print("🎉 Git security check passed!")
        print("💡 Remember to:")
        print("   - Rotate any previously exposed credentials")
        print("   - Never commit .env files")
        print("   - Use .env.example for templates")
    else:
        print("⚠️  Security issues found - please address them")
    
    return env_secure

if __name__ == "__main__":
    success = main()
    exit(0 if success else 1)