#!/usr/bin/env python3
"""
Create Clean Migration Script

This script creates a clean migration to resolve the user_permissions table
issues without dealing with complex migration conflicts.

Usage:
    python create_clean_migration.py
"""

import os
import sys
import django
from pathlib import Path

def setup_django():
    """Setup Django environment"""
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        django.setup()
        print("[SUCCESS] Django environment setup successful")
        return True
    except Exception as e:
        print(f"[ERROR] Django setup failed: {str(e)}")
        return False

def create_clean_migration():
    """Create a clean migration file"""
    print("=" * 60)
    print("CREATING CLEAN MIGRATION FOR USER_PERMISSIONS")
    print("=" * 60)
    
    if not setup_django():
        return False
    
    # Create the migration file content
    migration_content = '''# Generated manually to fix user_permissions table

from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0017_add_mpesa_fields_only'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserPermission',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('module', models.CharField(choices=[
                    ('dashboard', 'Dashboard'),
                    ('clients', 'Clients'),
                    ('loans', 'Loans'),
                    ('repayments', 'All Repayments'),
                    ('portfolio', 'Portfolio'),
                    ('reports_statements', 'Reports & Statements'),
                    ('documents', 'Documents'),
                    ('customer_documents', 'Customer Documents'),
                    ('payment_receipts', 'Payment Receipts'),
                    ('notifications', 'Notifications'),
                    ('settings', 'Settings'),
                    ('branch_settings', 'Branch Settings'),
                    ('system_settings', 'System Settings'),
                ], max_length=50)),
                ('action', models.CharField(choices=[
                    ('access', 'Access/View'),
                    ('create', 'Create/Add'),
                    ('edit', 'Edit/Modify'),
                    ('delete', 'Delete/Remove'),
                    ('approve', 'Approve'),
                    ('reject', 'Reject'),
                    ('verify', 'Verify'),
                    ('validate', 'Validate'),
                    ('export', 'Export'),
                    ('import', 'Import'),
                    ('download', 'Download'),
                    ('upload', 'Upload'),
                    ('print', 'Print'),
                    ('process', 'Process'),
                    ('calculate', 'Calculate'),
                    ('generate', 'Generate'),
                    ('record', 'Record'),
                    ('reconcile', 'Reconcile'),
                    ('assign', 'Assign'),
                    ('reassign', 'Reassign'),
                    ('manage', 'Manage'),
                    ('configure', 'Configure'),
                    ('send', 'Send'),
                    ('email', 'Email'),
                    ('notify', 'Notify'),
                    ('share', 'Share'),
                    ('activate', 'Activate'),
                    ('deactivate', 'Deactivate'),
                    ('suspend', 'Suspend'),
                    ('close', 'Close'),
                    ('monitor', 'Monitor'),
                    ('audit', 'Audit'),
                    ('backup', 'Backup'),
                    ('restore', 'Restore'),
                ], max_length=30)),
                ('is_allowed', models.BooleanField(default=False)),
                ('granted_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='permissions_granted', to=settings.AUTH_USER_MODEL)),
                ('reason', models.TextField(blank=True, help_text='Reason for custom permission', null=True)),
                ('expires_at', models.DateTimeField(blank=True, help_text='When this permission expires', null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='custom_permissions', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'db_table': 'user_permissions',
                'ordering': ['user', 'module', 'action'],
            },
        ),
        migrations.AddIndex(
            model_name='userpermission',
            index=models.Index(fields=['user', 'expires_at'], name='user_permis_user_id_718a3c_idx'),
        ),
        migrations.AddIndex(
            model_name='userpermission',
            index=models.Index(fields=['module', 'action'], name='user_permis_module_f508fb_idx'),
        ),
        migrations.AlterUniqueTogether(
            name='userpermission',
            unique_together={('user', 'module', 'action')},
        ),
    ]
'''
    
    # Write the migration file
    migration_file = Path('users/migrations/0023_create_user_permissions_clean.py')
    
    try:
        with open(migration_file, 'w', encoding='utf-8') as f:
            f.write(migration_content)
        print(f"[SUCCESS] Created migration file: {migration_file}")
        
        # Apply the migration
        print("Applying the migration...")
        import subprocess
        result = subprocess.run(
            ['python', 'manage.py', 'migrate', 'users', '0023'],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        
        if result.returncode == 0:
            print("[SUCCESS] Migration applied successfully")
            if result.stdout:
                print(f"Output: {result.stdout}")
        else:
            print(f"[ERROR] Migration failed: {result.stderr}")
            return False
        
        # Verify the fix
        print("Verifying the fix...")
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM user_permissions WHERE module = 'test'")
            result = cursor.fetchone()
            print("[SUCCESS] user_permissions table is working correctly")
            return True
            
    except Exception as e:
        print(f"[ERROR] Error creating migration: {str(e)}")
        return False

def main():
    """Main function"""
    try:
        success = create_clean_migration()
        
        if success:
            print("=" * 60)
            print("CLEAN MIGRATION CREATED SUCCESSFULLY!")
            print("The user_permissions table should now work correctly.")
            print("=" * 60)
        else:
            print("=" * 60)
            print("FAILED TO CREATE CLEAN MIGRATION")
            print("Please check the error messages above.")
            print("=" * 60)
        
        return success
        
    except Exception as e:
        print(f"Script failed: {str(e)}")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
