#!/usr/bin/env python3
"""
Fix all datetime.utcnow() deprecation issues for Python 3.12 compatibility
"""
import os
import re
from pathlib import Path

def fix_datetime_in_file(filepath):
    """Fix datetime.utcnow() to datetime.now(timezone.utc) in a file"""
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Check if file needs fixing
    if 'datetime.utcnow()' not in content:
        return False
    
    # Check if timezone is imported
    has_timezone = 'from datetime import' in content and 'timezone' in content
    
    if not has_timezone:
        # Add timezone to imports
        if 'from datetime import' in content:
            # Add timezone to existing import
            content = re.sub(
                r'from datetime import ([^\\n]+)',
                lambda m: f"from datetime import {m.group(1)}, timezone" if 'timezone' not in m.group(1) else m.group(0),
                content,
                count=1
            )
        else:
            # Add new import line after other imports
            lines = content.split('\n')
            import_idx = 0
            for i, line in enumerate(lines):
                if line.startswith('import ') or line.startswith('from '):
                    import_idx = i
            lines.insert(import_idx + 1, 'from datetime import timezone')
            content = '\n'.join(lines)
    
    # Replace all datetime.utcnow() with datetime.now(timezone.utc)
    content = content.replace('datetime.utcnow()', 'datetime.now(timezone.utc)')
    
    # Write back
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✅ Fixed: {filepath}")
    return True

def main():
    """Main function to fix all files"""
    print("Fixing datetime.utcnow() deprecation issues...")
    print("=" * 60)
    
    # Files to fix based on our search
    files_to_fix = [
        'app/models/contract.py',
        'app/models/message.py', 
        'app/models/notification.py'
    ]
    
    # Also search for any other Python files with the issue
    for root, dirs, files in os.walk('app'):
        for file in files:
            if file.endswith('.py'):
                filepath = os.path.join(root, file)
                if filepath.replace('\\', '/') not in files_to_fix:
                    try:
                        with open(filepath, 'r', encoding='utf-8') as f:
                            if 'datetime.utcnow()' in f.read():
                                files_to_fix.append(filepath.replace('\\', '/'))
                    except:
                        pass
    
    fixed_count = 0
    for filepath in files_to_fix:
        if os.path.exists(filepath):
            if fix_datetime_in_file(filepath):
                fixed_count += 1
        else:
            print(f"⚠️  File not found: {filepath}")
    
    print("=" * 60)
    print(f"✅ Fixed {fixed_count} files")
    print("\nAll datetime.utcnow() calls have been replaced with datetime.now(timezone.utc)")
    print("This ensures Python 3.12 compatibility.")

if __name__ == "__main__":
    main()
