#!/usr/bin/env python
"""
Script to clean up created_by and updated_by fields before migration.
This script sets all created_by and updated_by fields to NULL so they can be 
safely converted from CharField to ForeignKey.
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
django.setup()

from django.db import connection

def clean_user_fields():
    """Clean up created_by and updated_by fields in all tables"""
    
    with connection.cursor() as cursor:
        # Get all table names that have created_by and updated_by columns
        cursor.execute("""
            SELECT DISTINCT table_name 
            FROM information_schema.columns 
            WHERE table_schema = DATABASE() 
            AND column_name IN ('created_by', 'updated_by')
        """)
        
        tables = cursor.fetchall()
        
        print("Found tables with created_by/updated_by fields:")
        for table in tables:
            print(f"  - {table[0]}")
        
        print("\nCleaning up created_by and updated_by fields...")
        
        for table in tables:
            table_name = table[0]
            try:
                # Set created_by to NULL
                cursor.execute(f"UPDATE `{table_name}` SET created_by = NULL WHERE created_by IS NOT NULL")
                created_by_updated = cursor.rowcount
                
                # Set updated_by to NULL  
                cursor.execute(f"UPDATE `{table_name}` SET updated_by = NULL WHERE updated_by IS NOT NULL")
                updated_by_updated = cursor.rowcount
                
                print(f"  ✓ {table_name}: cleaned {created_by_updated} created_by, {updated_by_updated} updated_by")
                
            except Exception as e:
                print(f"  ✗ {table_name}: Error - {e}")
        
        print("\nCleanup completed! You can now run: python manage.py migrate")

if __name__ == "__main__":
    clean_user_fields()
