#!/usr/bin/env python
"""
Fix duplicate generated_by column issue
Removes the duplicate generated_by column to resolve the conflict
"""

import os
import sys
import django
from django.core.management import execute_from_command_line
from django.db import connection

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def fix_duplicate_generated_by_column():
    """Fix the duplicate generated_by column issue"""
    print("=== FIXING DUPLICATE GENERATED_BY COLUMN ===")
    
    with connection.cursor() as cursor:
        # Check current table structure
        cursor.execute("DESCRIBE generated_reports")
        columns = cursor.fetchall()
        
        print("Current generated_reports table structure:")
        for col in columns:
            print(f"  {col[0]} - {col[1]} - {col[2]} - {col[3]} - {col[4]} - {col[5]}")
        
        # Check if we have both generated_by and generated_by_id
        column_names = [col[0] for col in columns]
        
        if 'generated_by' in column_names and 'generated_by_id' in column_names:
            print("\n⚠ Found both 'generated_by' and 'generated_by_id' columns")
            print("  This is causing the duplicate column error")
            
            # Remove the old 'generated_by' column (keep 'generated_by_id')
            try:
                cursor.execute("ALTER TABLE generated_reports DROP COLUMN generated_by")
                print("✓ Removed duplicate 'generated_by' column")
            except Exception as e:
                print(f"⚠ Could not remove 'generated_by' column: {e}")
        else:
            print("✓ No duplicate generated_by columns found")
        
        # Check final table structure
        print("\nFinal generated_reports table structure:")
        cursor.execute("DESCRIBE generated_reports")
        columns = cursor.fetchall()
        for col in columns:
            print(f"  {col[0]} - {col[1]} - {col[2]} - {col[3]} - {col[4]} - {col[5]}")

def test_migrations():
    """Test that migrations work"""
    print("\n=== TESTING MIGRATIONS ===")
    
    try:
        # Test migrate
        print("  Testing migrate...")
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("    ✓ migrate works")
        
        return True
        
    except Exception as e:
        print(f"    ✗ Migration test failed: {e}")
        return False

def main():
    """Main fix function"""
    print("=== DUPLICATE GENERATED_BY COLUMN FIX ===")
    print("Removing the duplicate 'generated_by' column to resolve the conflict.\n")
    
    try:
        setup_django()
        
        # Fix duplicate generated_by column
        fix_duplicate_generated_by_column()
        
        # Test migrations
        if test_migrations():
            print("\n=== FIX COMPLETE ===")
            print("✓ Duplicate generated_by column issue has been resolved!")
            print("✓ Django migrations are working correctly")
            print("✓ All migration issues are now fixed")
            print("\n🎉 Your application should now work perfectly!")
            print("\n📋 Next steps:")
            print("1. Test your application: python manage.py runserver")
            print("2. Check the portfolio assignment page")
            print("3. Test the enhanced rollover functionality")
            return True
        else:
            print("\n=== FIX PARTIALLY COMPLETE ===")
            print("⚠ Duplicate generated_by column issue has been addressed")
            print("⚠ Some issues may remain")
            return False
        
    except Exception as e:
        print(f"\n❌ Fix failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
