#!/usr/bin/env python3
"""
Script to fix admin setup issues in AI reporting tests.

This script helps apply the admin permission fixes to all test files
that are experiencing "No admin recipients found" errors.
"""

import os
import re
import sys

def fix_admin_setup_in_file(file_path):
    """Fix admin setup in a specific test file"""
    print(f"Processing: {file_path}")
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    original_content = content
    changes_made = []
    
    # Pattern 1: Fix manual admin creation with permission setup
    old_pattern1 = r'''        self\.admin = User\.objects\.create_user\(
            phone='[^']*',
            email='[^']*',
            first_name='[^']*',
            last_name='[^']*',
            is_staff=True[^)]*
        \)
        
        self\.user = User\.objects\.create_user\(
            phone='[^']*',
            email='[^']*',
            first_name='[^']*',
            last_name='[^']*'
        \)
        
        # Give admin permission to receive emails
        # Clean up any existing permissions first
        Permission\.objects\.filter\(codename='can_receive_ai_report_emails'\)\.delete\(\)
        
        permission = Permission\.objects\.create\(
            codename='can_receive_ai_report_emails',
            name='Can receive AI analysis report emails',
            content_type_id=1
        \)
        self\.admin\.user_permissions\.add\(permission\)'''
    
    new_pattern1 = '''        # Use the fixed admin creation utility
        from tests.test_utils import create_admin_with_report_permissions
        
        self.admin = create_admin_with_report_permissions(
            phone='13800138001',
            email='admin@example.com',
            first_name='Admin',
            last_name='User'
        )
        
        self.user = User.objects.create_user(
            phone='13800138000',
            email='user@example.com',
            first_name='Test',
            last_name='User'
        )'''
    
    if re.search(old_pattern1, content, re.DOTALL):
        content = re.sub(old_pattern1, new_pattern1, content, flags=re.DOTALL)
        changes_made.append("Fixed manual admin creation pattern")
    
    # Pattern 2: Fix tearDown methods
    old_pattern2 = r'''    def tearDown\(self\):
        """Clean up test data"""
        Permission\.objects\.filter\(codename='can_receive_ai_report_emails'\)\.delete\(\)'''
    
    new_pattern2 = '''    def tearDown(self):
        """Clean up test data"""
        from tests.test_utils import cleanup_test_permissions
        cleanup_test_permissions()'''
    
    if re.search(old_pattern2, content):
        content = re.sub(old_pattern2, new_pattern2, content)
        changes_made.append("Fixed tearDown method")
    
    # Pattern 3: Add import if test_utils functions are used but not imported
    if 'create_admin_with_report_permissions' in content and 'from tests.test_utils import' not in content:
        # Add import after other imports
        import_pattern = r'(from django\.contrib\.auth\.models import Permission\n)'
        if re.search(import_pattern, content):
            content = re.sub(import_pattern, r'\1from tests.test_utils import create_admin_with_report_permissions, cleanup_test_permissions\n', content)
            changes_made.append("Added test_utils import")
    
    # Save the file if changes were made
    if content != original_content:
        with open(file_path, 'w') as f:
            f.write(content)
        print(f"  ✅ Changes made: {', '.join(changes_made)}")
        return True
    else:
        print(f"  ℹ️  No changes needed")
        return False

def main():
    """Main function to process all test files"""
    print("🔧 Fixing AI reporting test admin setup issues...")
    print("=" * 60)
    
    # Get the directory containing this script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # List of test files to process
    test_files = [
        'test_reporting_emails.py',
        'test_reporting_admin.py',
        'test_reporting_api.py',
        'test_reporting_integration.py',
        'test_reporting_models.py'
    ]
    
    fixed_files = 0
    total_files = 0
    
    for test_file in test_files:
        file_path = os.path.join(script_dir, test_file)
        if os.path.exists(file_path):
            total_files += 1
            if fix_admin_setup_in_file(file_path):
                fixed_files += 1
        else:
            print(f"⚠️  File not found: {file_path}")
    
    print("\n" + "=" * 60)
    print(f"📊 Summary: Fixed {fixed_files} out of {total_files} files")
    
    if fixed_files > 0:
        print("\n✅ Admin setup fixes applied successfully!")
        print("\nNext steps:")
        print("1. Run your tests to verify they pass")
        print("2. Check for any remaining 'No admin recipients found' errors")
        print("3. Use create_admin_with_report_permissions() in any new tests")
    else:
        print("\n✅ All files are already properly configured!")

if __name__ == "__main__":
    main() 