import os
import sys
import django
import logging
from django.db import connection
from django.core.management import execute_from_command_line

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

def check_and_fix_custom_user_tables():
    """Check and fix all Django custom user related tables"""
    try:
        with connection.cursor() as cursor:
            logger.info("Checking Django custom user table structure...")
            
            # Get the actual table name for users
            cursor.execute("""
                SELECT table_name 
                FROM information_schema.tables 
                WHERE table_schema = DATABASE() 
                AND table_name LIKE '%user%'
                ORDER BY table_name
            """)
            
            tables = [row[0] for row in cursor.fetchall()]
            logger.info(f"Found user-related tables: {tables}")
            
            # Check if we have the main users table
            if 'users' not in tables:
                logger.error("❌ Main 'users' table not found!")
                return False
            
            # Drop existing problematic tables
            problematic_tables = [
                'users_groups',
                'users_user_permissions',
                'users_customuser_groups',
                'users_customuser_user_permissions'
            ]
            
            for table in problematic_tables:
                if table in tables:
                    logger.info(f"Dropping problematic table: {table}")
                    cursor.execute(f"DROP TABLE IF EXISTS {table}")
            
            # Create the correct many-to-many tables for Django custom user
            logger.info("Creating users_customuser_groups table...")
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS users_customuser_groups (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    customuser_id INT NOT NULL,
                    group_id INT NOT NULL,
                    UNIQUE KEY users_customuser_groups_customuser_id_group_id_uniq (customuser_id, group_id),
                    KEY users_customuser_groups_customuser_id (customuser_id),
                    KEY users_customuser_groups_group_id (group_id),
                    CONSTRAINT users_customuser_groups_customuser_id_fk 
                        FOREIGN KEY (customuser_id) REFERENCES users (id) ON DELETE CASCADE,
                    CONSTRAINT users_customuser_groups_group_id_fk 
                        FOREIGN KEY (group_id) REFERENCES auth_group (id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """)
            
            logger.info("Creating users_customuser_user_permissions table...")
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS users_customuser_user_permissions (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    customuser_id INT NOT NULL,
                    permission_id INT NOT NULL,
                    UNIQUE KEY users_customuser_user_permissions_customuser_id_permission_id_uniq (customuser_id, permission_id),
                    KEY users_customuser_user_permissions_customuser_id (customuser_id),
                    KEY users_customuser_user_permissions_permission_id (permission_id),
                    CONSTRAINT users_customuser_user_permissions_customuser_id_fk 
                        FOREIGN KEY (customuser_id) REFERENCES users (id) ON DELETE CASCADE,
                    CONSTRAINT users_customuser_user_permissions_permission_id_fk 
                        FOREIGN KEY (permission_id) REFERENCES auth_permission (id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """)
            
            logger.info("✅ Django custom user tables created successfully")
            return True
            
    except Exception as e:
        logger.error(f"❌ Error fixing Django custom user tables: {e}")
        return False

def update_django_content_types():
    """Update Django content types to match our custom user model"""
    try:
        with connection.cursor() as cursor:
            logger.info("Updating Django content types...")
            
            # Update content type for our custom user model
            cursor.execute("""
                UPDATE django_content_type 
                SET model = 'customuser' 
                WHERE app_label = 'users' AND model = 'user'
            """)
            
            # Ensure we have the correct content type
            cursor.execute("""
                INSERT IGNORE INTO django_content_type (app_label, model) 
                VALUES ('users', 'customuser')
            """)
            
            logger.info("✅ Django content types updated")
            return True
            
    except Exception as e:
        logger.error(f"❌ Error updating content types: {e}")
        return False

def create_fake_migration():
    """Create a fake migration to mark tables as migrated"""
    try:
        logger.info("Creating fake migration for custom user tables...")
        
        # Create a simple migration file
        migration_content = '''
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('users', '0013_customuser_accessible_branches'),
    ]
    
    operations = [
        # This is a fake migration to mark custom user tables as migrated
        migrations.RunSQL("SELECT 1;", reverse_sql="SELECT 1;"),
    ]
'''
        
        # Write the migration file
        migration_dir = 'users/migrations'
        if not os.path.exists(migration_dir):
            os.makedirs(migration_dir)
        
        migration_file = os.path.join(migration_dir, '0014_fix_custom_user_tables.py')
        with open(migration_file, 'w') as f:
            f.write(migration_content)
        
        logger.info(f"✅ Created fake migration: {migration_file}")
        return True
        
    except Exception as e:
        logger.error(f"❌ Error creating fake migration: {e}")
        return False

def test_client_creation_final():
    """Final test of client creation with proper error handling"""
    try:
        from users.models import CustomUser, Branch
        from django.contrib.auth.models import Group
        from django.db import transaction
        
        logger.info("Testing client creation with transaction handling...")
        
        # Get or create a branch
        branch, created = Branch.objects.get_or_create(
            name="Main Branch",
            defaults={
                'code': 'MAIN',
                'is_main_branch': True,
                'is_active': True
            }
        )
        
        # Try to create a test client with transaction
        test_email = "test_final@example.com"
        test_phone = "+1234567890124"
        
        # Delete existing test user if exists
        CustomUser.objects.filter(email=test_email).delete()
        CustomUser.objects.filter(phone_number=test_phone).delete()
        
        with transaction.atomic():
            # Create test client
            user = CustomUser.objects.create_user(
                username=test_email,
                email=test_email,
                phone_number=test_phone,
                first_name="Test",
                last_name="Final",
                role="client",
                branch=branch
            )
            
            # Test adding to groups
            client_group, created = Group.objects.get_or_create(name='Clients')
            user.groups.add(client_group)
            user.save()
            
            logger.info(f"✅ Successfully created test client: {user.get_full_name()}")
            logger.info(f"✅ User ID: {user.id}, Groups: {[g.name for g in user.groups.all()]}")
            
            # Test duplicate detection
            try:
                duplicate_user = CustomUser.objects.create_user(
                    username=test_email + "_dup",
                    email=test_email,  # Same email
                    phone_number="+9999999999",
                    first_name="Duplicate",
                    last_name="Test",
                    role="client",
                    branch=branch
                )
                logger.error("❌ Duplicate detection failed - should not create user with same email")
                duplicate_user.delete()
            except Exception as e:
                logger.info(f"✅ Duplicate detection working: {str(e)[:100]}...")
            
            # Clean up
            user.delete()
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Client creation test failed: {e}")
        import traceback
        logger.error(f"Full traceback: {traceback.format_exc()}")
        return False

def main():
    """Main function to fix all Django custom user issues"""
    logger.info("="*80)
    logger.info("DJANGO CUSTOM USER TABLES COMPREHENSIVE FIX")
    logger.info("="*80)
    
    success_count = 0
    total_steps = 4
    
    # Step 1: Fix Django custom user tables
    logger.info("\nStep 1: Fixing Django custom user tables...")
    if check_and_fix_custom_user_tables():
        success_count += 1
    
    # Step 2: Update content types
    logger.info("\nStep 2: Updating Django content types...")
    if update_django_content_types():
        success_count += 1
    
    # Step 3: Create fake migration
    logger.info("\nStep 3: Creating fake migration...")
    if create_fake_migration():
        success_count += 1
    
    # Step 4: Test client creation
    logger.info("\nStep 4: Testing client creation...")
    if test_client_creation_final():
        success_count += 1
    
    # Final summary
    logger.info("\n" + "="*80)
    logger.info("FINAL SUMMARY")
    logger.info("="*80)
    logger.info(f"Completed {success_count}/{total_steps} steps successfully")
    
    if success_count == total_steps:
        logger.info("✅ All Django custom user issues fixed successfully!")
        logger.info("\nYour client creation should now work properly.")
        logger.info("\nNext steps:")
        logger.info("1. Restart your Django application")
        logger.info("2. Try creating a client through the web interface")
        logger.info("3. Check that no duplicate errors occur")
    else:
        logger.info(f"⚠️  {total_steps - success_count} steps failed - manual intervention may be needed")
        logger.info("\nIf issues persist, you may need to:")
        logger.info("1. Run: python manage.py migrate --fake users 0014")
        logger.info("2. Check your Django settings for AUTH_USER_MODEL")
        logger.info("3. Verify database permissions")
    
    logger.info("\n" + "="*80)
    logger.info("SCRIPT COMPLETED")
    logger.info("="*80)

if __name__ == "__main__":
    main()