#!/usr/bin/env python3
"""
Script to update the permissions structure to use the new enhanced page-specific permissions
"""

import os
import sys
import django

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'loans.settings')
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

django.setup()

from django.db import transaction
from users.models import CustomUser, RolePermission, UserPermission, DefaultRolePermission


def update_permissions_structure():
    """Update the permissions structure to use the new enhanced system"""
    
    print("🔄 Starting permissions structure update...")
    
    try:
        with transaction.atomic():
            # Clear existing permissions to start fresh
            print("📝 Clearing existing permissions...")
            RolePermission.objects.all().delete()
            DefaultRolePermission.objects.all().delete()
            UserPermission.objects.all().delete()
            
            # Define default permissions for each role based on the new structure
            default_permissions = {
                'admin': {
                    # Admin has access to everything
                    'dashboard': ['access'],
                    'dashboard_overview': ['access'],
                    'dashboard_metrics': ['access'],
                    'dashboard_charts': ['access'],
                    'dashboard_recent_activities': ['access'],
                    'dashboard_quick_actions': ['access'],
                    'dashboard_loan_summary': ['access'],
                    'dashboard_collection_summary': ['access'],
                    'dashboard_branch_performance': ['access'],
                    'dashboard_alerts': ['access'],
                    
                    'clients': ['access'],
                    'clients_view_list': ['access'],
                    'clients_search_filter': ['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'],
                    'clients_bulk_actions': ['manage'],
                    
                    'loans': ['access'],
                    'loans_view_list': ['access'],
                    'loans_search_filter': ['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_amortization_schedule': ['access'],
                    'loans_rollover_loan': ['process'],
                    'loans_calculate_interest': ['calculate'],
                    'loans_generate_receipt': ['generate'],
                    'loans_modify_terms': ['edit'],
                    'loans_close_loan': ['close'],
                    'loans_export_data': ['export'],
                    
                    'repayments': ['access'],
                    'repayments_view_list': ['access'],
                    'repayments_search_filter': ['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_bulk_import': ['import'],
                    'repayments_export_data': ['export'],
                    'repayments_view_analytics': ['access'],
                    
                    'portfolio': ['access'],
                    'portfolio_view_overview': ['access'],
                    'portfolio_manager_stats': ['access'],
                    'portfolio_performance_metrics': ['access'],
                    'portfolio_client_assignments': ['manage'],
                    'portfolio_reassign_clients': ['reassign'],
                    'portfolio_view_analytics': ['access'],
                    'portfolio_generate_reports': ['generate'],
                    'portfolio_target_tracking': ['access'],
                    
                    'reports_statements': ['access'],
                    'reports_view_dashboard': ['access'],
                    'reports_loans_due': ['access'],
                    'reports_delinquent_loans': ['access'],
                    'reports_arrears_analysis': ['access'],
                    'reports_processing_fees': ['access'],
                    'reports_interest_income': ['access'],
                    'reports_registration_fees': ['access'],
                    'reports_customer_requests': ['access'],
                    'reports_collection_summary': ['access'],
                    'reports_branch_performance': ['access'],
                    'reports_export_all': ['export'],
                    'reports_schedule_automated': ['configure'],
                    'statements_generate_loan': ['generate'],
                    'statements_generate_client': ['generate'],
                    'statements_download_pdf': ['download'],
                    'statements_email_client': ['email'],
                    
                    'documents': ['access'],
                    'documents_view_library': ['access'],
                    'documents_upload_files': ['upload'],
                    'documents_download_files': ['download'],
                    'documents_delete_files': ['delete'],
                    'documents_organize_folders': ['manage'],
                    'documents_search_content': ['access'],
                    'documents_share_access': ['share'],
                    'documents_version_control': ['manage'],
                    
                    'customer_documents': ['access'],
                    'customer_docs_view_all': ['access'],
                    'customer_docs_upload_kyc': ['upload'],
                    'customer_docs_verify_identity': ['verify'],
                    'customer_docs_approve_kyc': ['approve'],
                    'customer_docs_reject_kyc': ['reject'],
                    'customer_docs_request_additional': ['create'],
                    'customer_docs_download_files': ['download'],
                    'customer_docs_compliance_check': ['verify'],
                    
                    'payment_receipts': ['access'],
                    'receipts_view_all': ['access'],
                    'receipts_generate_new': ['generate'],
                    'receipts_edit_existing': ['edit'],
                    'receipts_delete_receipt': ['delete'],
                    'receipts_print_receipt': ['print'],
                    'receipts_download_pdf': ['download'],
                    'receipts_email_client': ['email'],
                    'receipts_bulk_generate': ['generate'],
                    'receipts_template_manage': ['manage'],
                    
                    'notifications': ['access'],
                    'notifications_view_inbox': ['access'],
                    'notifications_send_individual': ['send'],
                    'notifications_send_bulk': ['send'],
                    'notifications_manage_templates': ['manage'],
                    'notifications_configure_settings': ['configure'],
                    'notifications_view_history': ['access'],
                    'notifications_manage_channels': ['manage'],
                    
                    'settings': ['access'],
                    'settings_view_general': ['access'],
                    'settings_edit_system': ['edit'],
                    'settings_manage_users': ['manage'],
                    'settings_configure_permissions': ['configure'],
                    'settings_backup_restore': ['manage'],
                    'settings_integration_config': ['configure'],
                    'settings_audit_logs': ['access'],
                    
                    'branch_settings': ['access'],
                    'branch_view_info': ['access'],
                    'branch_edit_details': ['edit'],
                    'branch_manage_staff': ['manage'],
                    'branch_configure_mpesa': ['configure'],
                    'branch_view_performance': ['access'],
                    'branch_manage_targets': ['manage'],
                    
                    'system_settings': ['access'],
                    'system_database_management': ['manage'],
                    'system_server_monitoring': ['monitor'],
                    'system_security_settings': ['configure'],
                    'system_maintenance_mode': ['manage'],
                    'system_api_management': ['manage'],
                    'system_integration_logs': ['access'],
                },
                
                'team_leader': {
                    # Team leaders have most permissions except system administration
                    'dashboard': ['access'],
                    'dashboard_overview': ['access'],
                    'dashboard_metrics': ['access'],
                    'dashboard_charts': ['access'],
                    'dashboard_recent_activities': ['access'],
                    'dashboard_quick_actions': ['access'],
                    'dashboard_loan_summary': ['access'],
                    'dashboard_collection_summary': ['access'],
                    'dashboard_branch_performance': ['access'],
                    
                    'clients': ['access'],
                    'clients_view_list': ['access'],
                    'clients_search_filter': ['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': ['access'],
                    'loans_view_list': ['access'],
                    'loans_search_filter': ['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_amortization_schedule': ['access'],
                    'loans_rollover_loan': ['process'],
                    'loans_calculate_interest': ['calculate'],
                    'loans_generate_receipt': ['generate'],
                    'loans_modify_terms': ['edit'],
                    'loans_close_loan': ['close'],
                    'loans_export_data': ['export'],
                    
                    'repayments': ['access'],
                    'repayments_view_list': ['access'],
                    'repayments_search_filter': ['access'],
                    'repayments_record_payment': ['create'],
                    'repayments_edit_payment': ['edit'],
                    'repayments_verify_payment': ['verify'],
                    'repayments_reconcile_mpesa': ['reconcile'],
                    'repayments_generate_receipt': ['generate'],
                    'repayments_export_data': ['export'],
                    'repayments_view_analytics': ['access'],
                    
                    'portfolio': ['access'],
                    'portfolio_view_overview': ['access'],
                    'portfolio_manager_stats': ['access'],
                    'portfolio_performance_metrics': ['access'],
                    'portfolio_client_assignments': ['manage'],
                    'portfolio_reassign_clients': ['reassign'],
                    'portfolio_view_analytics': ['access'],
                    'portfolio_generate_reports': ['generate'],
                    
                    'reports_statements': ['access'],
                    'reports_view_dashboard': ['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_branch_performance': ['access'],
                    'reports_export_all': ['export'],
                    'statements_generate_loan': ['generate'],
                    'statements_generate_client': ['generate'],
                    'statements_download_pdf': ['download'],
                    
                    'documents': ['access'],
                    'documents_view_library': ['access'],
                    'documents_upload_files': ['upload'],
                    'documents_download_files': ['download'],
                    'documents_organize_folders': ['manage'],
                    
                    'customer_documents': ['access'],
                    'customer_docs_view_all': ['access'],
                    'customer_docs_upload_kyc': ['upload'],
                    'customer_docs_verify_identity': ['verify'],
                    'customer_docs_approve_kyc': ['approve'],
                    'customer_docs_reject_kyc': ['reject'],
                    
                    'payment_receipts': ['access'],
                    'receipts_view_all': ['access'],
                    'receipts_generate_new': ['generate'],
                    'receipts_print_receipt': ['print'],
                    'receipts_download_pdf': ['download'],
                    
                    'notifications': ['access'],
                    'notifications_view_inbox': ['access'],
                    'notifications_send_individual': ['send'],
                    'notifications_send_bulk': ['send'],
                    
                    'branch_settings': ['access'],
                    'branch_view_info': ['access'],
                    'branch_edit_details': ['edit'],
                    'branch_manage_staff': ['manage'],
                    'branch_view_performance': ['access'],
                },
                
                'loan_officer': {
                    # Loan officers focus on client and loan management
                    'dashboard': ['access'],
                    'dashboard_overview': ['access'],
                    'dashboard_metrics': ['access'],
                    'dashboard_loan_summary': ['access'],
                    'dashboard_collection_summary': ['access'],
                    
                    'clients': ['access'],
                    'clients_view_list': ['access'],
                    'clients_search_filter': ['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'],
                    'clients_export_data': ['export'],
                    
                    'loans': ['access'],
                    'loans_view_list': ['access'],
                    'loans_search_filter': ['access'],
                    'loans_create_application': ['create'],
                    'loans_edit_application': ['edit'],
                    'loans_view_details': ['access'],
                    'loans_amortization_schedule': ['access'],
                    'loans_calculate_interest': ['calculate'],
                    'loans_generate_receipt': ['generate'],
                    'loans_export_data': ['export'],
                    
                    'repayments': ['access'],
                    'repayments_view_list': ['access'],
                    'repayments_search_filter': ['access'],
                    'repayments_record_payment': ['create'],
                    'repayments_generate_receipt': ['generate'],
                    'repayments_view_analytics': ['access'],
                    
                    'portfolio': ['access'],
                    'portfolio_view_overview': ['access'],
                    'portfolio_performance_metrics': ['access'],
                    'portfolio_view_analytics': ['access'],
                    
                    'reports_statements': ['access'],
                    'reports_view_dashboard': ['access'],
                    'reports_loans_due': ['access'],
                    'reports_collection_summary': ['access'],
                    'statements_generate_loan': ['generate'],
                    'statements_generate_client': ['generate'],
                    
                    'customer_documents': ['access'],
                    'customer_docs_view_all': ['access'],
                    'customer_docs_upload_kyc': ['upload'],
                    
                    'payment_receipts': ['access'],
                    'receipts_view_all': ['access'],
                    'receipts_generate_new': ['generate'],
                    'receipts_print_receipt': ['print'],
                    
                    'notifications': ['access'],
                    'notifications_view_inbox': ['access'],
                },
                
                'secretary': {
                    # Secretaries focus on documentation and basic client management
                    'dashboard': ['access'],
                    'dashboard_overview': ['access'],
                    
                    'clients': ['access'],
                    'clients_view_list': ['access'],
                    'clients_search_filter': ['access'],
                    'clients_create_new': ['create'],
                    'clients_view_details': ['access'],
                    'clients_kyc_documents': ['access'],
                    
                    'documents': ['access'],
                    'documents_view_library': ['access'],
                    'documents_upload_files': ['upload'],
                    'documents_download_files': ['download'],
                    'documents_organize_folders': ['manage'],
                    
                    'customer_documents': ['access'],
                    'customer_docs_view_all': ['access'],
                    'customer_docs_upload_kyc': ['upload'],
                    
                    'payment_receipts': ['access'],
                    'receipts_view_all': ['access'],
                    'receipts_generate_new': ['generate'],
                    'receipts_print_receipt': ['print'],
                    
                    'notifications': ['access'],
                    'notifications_view_inbox': ['access'],
                    'notifications_send_individual': ['send'],
                },
            }
            
            # Create default permissions
            permissions_created = 0
            for role, modules in default_permissions.items():
                print(f"📋 Creating permissions for {role}...")
                
                for module, actions in modules.items():
                    for action in actions:
                        # 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
            
            print(f"✅ Successfully created {permissions_created} permissions")
            
            # Update existing users to ensure they have proper role assignments
            users_updated = 0
            for user in CustomUser.objects.filter(role__in=['admin', 'team_leader', 'loan_officer', 'secretary']):
                # Ensure admin users have proper staff status
                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
            
            print(f"✅ Updated {users_updated} user accounts")
            
            print("🎉 Permissions structure update completed successfully!")
            
    except Exception as e:
        print(f"❌ Error updating permissions structure: {e}")
        raise


if __name__ == '__main__':
    update_permissions_structure()