from django.core.management.base import BaseCommand
from django.db import transaction
from users.models import CustomUser, RolePermission, UserPermission, DefaultRolePermission


class Command(BaseCommand):
    help = 'Update permissions structure to use enhanced page-specific permissions'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('🔄 Starting enhanced permissions update...'))
        
        try:
            with transaction.atomic():
                # Clear existing permissions
                self.stdout.write('📝 Clearing existing permissions...')
                RolePermission.objects.all().delete()
                DefaultRolePermission.objects.all().delete()
                UserPermission.objects.all().delete()
                
                # Define simplified default permissions for each role
                default_permissions = {
                    'admin': [
                        # Dashboard
                        ('dashboard', 'access'),
                        ('dashboard_overview', 'access'),
                        ('dashboard_metrics', 'access'),
                        ('dashboard_charts', 'access'),
                        
                        # Clients - Full access
                        ('clients', 'access'),
                        ('clients_view_list', 'access'),
                        ('clients_create_new', 'create'),
                        ('clients_edit_profile', 'edit'),
                        ('clients_delete_client', 'delete'),
                        ('clients_view_details', 'access'),
                        ('clients_loan_history', 'access'),
                        ('clients_payment_history', 'access'),
                        ('clients_kyc_documents', 'access'),
                        ('clients_assign_portfolio', 'assign'),
                        ('clients_registration_fee', 'manage'),
                        ('clients_status_change', 'edit'),
                        ('clients_export_data', 'export'),
                        
                        # Loans - Full access
                        ('loans', 'access'),
                        ('loans_view_list', 'access'),
                        ('loans_create_application', 'create'),
                        ('loans_edit_application', 'edit'),
                        ('loans_delete_loan', 'delete'),
                        ('loans_approve_application', 'approve'),
                        ('loans_reject_application', 'reject'),
                        ('loans_disburse_funds', 'process'),
                        ('loans_view_details', 'access'),
                        ('loans_rollover_loan', 'process'),
                        ('loans_calculate_interest', 'calculate'),
                        ('loans_generate_receipt', 'generate'),
                        ('loans_modify_terms', 'edit'),
                        ('loans_close_loan', 'close'),
                        
                        # Repayments - Full access
                        ('repayments', 'access'),
                        ('repayments_view_list', 'access'),
                        ('repayments_record_payment', 'create'),
                        ('repayments_edit_payment', 'edit'),
                        ('repayments_delete_payment', 'delete'),
                        ('repayments_verify_payment', 'verify'),
                        ('repayments_reconcile_mpesa', 'reconcile'),
                        ('repayments_generate_receipt', 'generate'),
                        ('repayments_view_analytics', 'access'),
                        ('repayments_export_data', 'export'),
                        
                        # Portfolio - Full access
                        ('portfolio', 'access'),
                        ('portfolio_view_overview', 'access'),
                        ('portfolio_performance_metrics', 'access'),
                        ('portfolio_client_assignments', 'manage'),
                        ('portfolio_reassign_clients', 'reassign'),
                        ('portfolio_view_analytics', 'access'),
                        ('portfolio_generate_reports', 'generate'),
                        
                        # Reports - Full access
                        ('reports_statements', 'access'),
                        ('reports_loans_due', 'access'),
                        ('reports_delinquent_loans', 'access'),
                        ('reports_processing_fees', 'access'),
                        ('reports_interest_income', 'access'),
                        ('reports_registration_fees', 'access'),
                        ('reports_collection_summary', 'access'),
                        ('reports_export_all', 'export'),
                        ('statements_generate_loan', 'generate'),
                        ('statements_generate_client', 'generate'),
                        ('statements_download_pdf', 'download'),
                        ('statements_email_client', 'email'),
                        
                        # Documents - Full access
                        ('documents', 'access'),
                        ('documents_upload_files', 'upload'),
                        ('documents_download_files', 'download'),
                        ('documents_delete_files', 'delete'),
                        
                        # Customer Documents - Full access
                        ('customer_documents', 'access'),
                        ('customer_docs_upload_kyc', 'upload'),
                        ('customer_docs_verify_identity', 'verify'),
                        ('customer_docs_approve_kyc', 'approve'),
                        
                        # Payment Receipts - Full access
                        ('payment_receipts', 'access'),
                        ('receipts_generate_new', 'generate'),
                        ('receipts_print_receipt', 'print'),
                        ('receipts_email_client', 'email'),
                        
                        # Notifications - Full access
                        ('notifications', 'access'),
                        ('notifications_send_individual', 'send'),
                        ('notifications_send_bulk', 'send'),
                        ('notifications_manage_templates', 'manage'),
                        
                        # Settings - Full access
                        ('settings', 'access'),
                        ('settings_edit_system', 'edit'),
                        ('settings_manage_users', 'manage'),
                        ('branch_settings', 'access'),
                        ('branch_edit_details', 'edit'),
                        ('branch_configure_mpesa', 'configure'),
                        ('system_settings', 'access'),
                        ('system_database_management', 'manage'),
                        ('system_security_settings', 'configure'),
                    ],
                    
                    'team_leader': [
                        # Dashboard
                        ('dashboard', 'access'),
                        ('dashboard_overview', 'access'),
                        ('dashboard_metrics', 'access'),
                        ('dashboard_charts', 'access'),
                        
                        # Clients - Most access except delete
                        ('clients', 'access'),
                        ('clients_view_list', 'access'),
                        ('clients_create_new', 'create'),
                        ('clients_edit_profile', 'edit'),
                        ('clients_view_details', 'access'),
                        ('clients_loan_history', 'access'),
                        ('clients_payment_history', 'access'),
                        ('clients_kyc_documents', 'access'),
                        ('clients_assign_portfolio', 'assign'),
                        ('clients_registration_fee', 'manage'),
                        ('clients_status_change', 'edit'),
                        ('clients_export_data', 'export'),
                        
                        # Loans - Full access
                        ('loans', 'access'),
                        ('loans_view_list', 'access'),
                        ('loans_create_application', 'create'),
                        ('loans_edit_application', 'edit'),
                        ('loans_approve_application', 'approve'),
                        ('loans_reject_application', 'reject'),
                        ('loans_disburse_funds', 'process'),
                        ('loans_view_details', 'access'),
                        ('loans_rollover_loan', 'process'),
                        ('loans_calculate_interest', 'calculate'),
                        ('loans_generate_receipt', 'generate'),
                        ('loans_modify_terms', 'edit'),
                        ('loans_close_loan', 'close'),
                        
                        # Repayments - Most access except delete
                        ('repayments', 'access'),
                        ('repayments_view_list', 'access'),
                        ('repayments_record_payment', 'create'),
                        ('repayments_edit_payment', 'edit'),
                        ('repayments_verify_payment', 'verify'),
                        ('repayments_reconcile_mpesa', 'reconcile'),
                        ('repayments_generate_receipt', 'generate'),
                        ('repayments_view_analytics', 'access'),
                        ('repayments_export_data', 'export'),
                        
                        # Portfolio - Full access
                        ('portfolio', 'access'),
                        ('portfolio_view_overview', 'access'),
                        ('portfolio_performance_metrics', 'access'),
                        ('portfolio_client_assignments', 'manage'),
                        ('portfolio_reassign_clients', 'reassign'),
                        ('portfolio_view_analytics', 'access'),
                        ('portfolio_generate_reports', 'generate'),
                        
                        # Reports - Full access
                        ('reports_statements', 'access'),
                        ('reports_loans_due', 'access'),
                        ('reports_delinquent_loans', 'access'),
                        ('reports_processing_fees', 'access'),
                        ('reports_interest_income', 'access'),
                        ('reports_collection_summary', 'access'),
                        ('reports_export_all', 'export'),
                        ('statements_generate_loan', 'generate'),
                        ('statements_generate_client', 'generate'),
                        ('statements_download_pdf', 'download'),
                        
                        # Documents - Most access
                        ('documents', 'access'),
                        ('documents_upload_files', 'upload'),
                        ('documents_download_files', 'download'),
                        
                        # Customer Documents - Full access
                        ('customer_documents', 'access'),
                        ('customer_docs_upload_kyc', 'upload'),
                        ('customer_docs_verify_identity', 'verify'),
                        ('customer_docs_approve_kyc', 'approve'),
                        
                        # Payment Receipts - Full access
                        ('payment_receipts', 'access'),
                        ('receipts_generate_new', 'generate'),
                        ('receipts_print_receipt', 'print'),
                        
                        # Notifications - Most access
                        ('notifications', 'access'),
                        ('notifications_send_individual', 'send'),
                        ('notifications_send_bulk', 'send'),
                        
                        # Branch Settings only
                        ('branch_settings', 'access'),
                        ('branch_view_info', 'access'),
                        ('branch_edit_details', 'edit'),
                        ('branch_manage_staff', 'manage'),
                    ],
                    
                    'loan_officer': [
                        # Dashboard - Basic access
                        ('dashboard', 'access'),
                        ('dashboard_overview', 'access'),
                        ('dashboard_metrics', 'access'),
                        
                        # Clients - Basic management
                        ('clients', 'access'),
                        ('clients_view_list', 'access'),
                        ('clients_create_new', 'create'),
                        ('clients_edit_profile', 'edit'),
                        ('clients_view_details', 'access'),
                        ('clients_loan_history', 'access'),
                        ('clients_payment_history', 'access'),
                        ('clients_kyc_documents', 'access'),
                        ('clients_registration_fee', 'manage'),
                        
                        # Loans - Create and manage but not approve
                        ('loans', 'access'),
                        ('loans_view_list', 'access'),
                        ('loans_create_application', 'create'),
                        ('loans_edit_application', 'edit'),
                        ('loans_view_details', 'access'),
                        ('loans_calculate_interest', 'calculate'),
                        ('loans_generate_receipt', 'generate'),
                        
                        # Repayments - Record and view
                        ('repayments', 'access'),
                        ('repayments_view_list', 'access'),
                        ('repayments_record_payment', 'create'),
                        ('repayments_generate_receipt', 'generate'),
                        ('repayments_view_analytics', 'access'),
                        
                        # Portfolio - View only
                        ('portfolio', 'access'),
                        ('portfolio_view_overview', 'access'),
                        ('portfolio_performance_metrics', 'access'),
                        
                        # Reports - Basic reports
                        ('reports_statements', 'access'),
                        ('reports_loans_due', 'access'),
                        ('reports_collection_summary', 'access'),
                        ('statements_generate_loan', 'generate'),
                        ('statements_generate_client', 'generate'),
                        
                        # Customer Documents - Upload and view
                        ('customer_documents', 'access'),
                        ('customer_docs_upload_kyc', 'upload'),
                        
                        # Payment Receipts - Generate and print
                        ('payment_receipts', 'access'),
                        ('receipts_generate_new', 'generate'),
                        ('receipts_print_receipt', 'print'),
                        
                        # Notifications - View only
                        ('notifications', 'access'),
                    ],
                    
                    'secretary': [
                        # Dashboard - Basic view
                        ('dashboard', 'access'),
                        ('dashboard_overview', 'access'),
                        
                        # Clients - Basic management
                        ('clients', 'access'),
                        ('clients_view_list', 'access'),
                        ('clients_create_new', 'create'),
                        ('clients_view_details', 'access'),
                        ('clients_kyc_documents', 'access'),
                        
                        # Documents - Full access
                        ('documents', 'access'),
                        ('documents_upload_files', 'upload'),
                        ('documents_download_files', 'download'),
                        
                        # Customer Documents - Upload and organize
                        ('customer_documents', 'access'),
                        ('customer_docs_upload_kyc', 'upload'),
                        
                        # Payment Receipts - Generate and print
                        ('payment_receipts', 'access'),
                        ('receipts_generate_new', 'generate'),
                        ('receipts_print_receipt', 'print'),
                        
                        # Notifications - Send individual
                        ('notifications', 'access'),
                        ('notifications_send_individual', 'send'),
                    ],
                }
                
                # Create permissions
                permissions_created = 0
                for role, permissions in default_permissions.items():
                    self.stdout.write(f'📋 Creating permissions for {role}...')
                    
                    for module, action in permissions:
                        # Create default role permission
                        DefaultRolePermission.objects.create(
                            role=role,
                            module=module,
                            action=action,
                            is_allowed=True,
                            description=f"Default {action} permission for {module}"
                        )
                        
                        # Create role permission
                        RolePermission.objects.create(
                            role=role,
                            module=module,
                            action=action,
                            is_allowed=True
                        )
                        
                        permissions_created += 1
                
                self.stdout.write(
                    self.style.SUCCESS(f'✅ Successfully created {permissions_created} permissions')
                )
                
                # Update user accounts
                users_updated = 0
                for user in CustomUser.objects.filter(role__in=['admin', 'team_leader', 'loan_officer', 'secretary']):
                    if user.role == 'admin':
                        user.is_staff = True
                        user.is_superuser = True
                    elif user.role in ['team_leader', 'loan_officer', 'secretary']:
                        user.is_staff = True
                        user.is_superuser = False
                    
                    user.save()
                    users_updated += 1
                
                self.stdout.write(
                    self.style.SUCCESS(f'✅ Updated {users_updated} user accounts')
                )
                
                self.stdout.write(
                    self.style.SUCCESS('🎉 Enhanced permissions update completed successfully!')
                )
                
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ Error updating permissions: {e}')
            )
            raise