"""
Management command to seed default role permission templates
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from users.enhanced_permissions_models import PagePermission, RolePermissionTemplate


class Command(BaseCommand):
    help = 'Seed default role permission templates for all roles'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing role templates before seeding',
        )

    def handle(self, *args, **options):
        if options['clear']:
            self.stdout.write('Clearing existing role templates...')
            RolePermissionTemplate.objects.all().delete()

        with transaction.atomic():
            self.stdout.write('Seeding role permission templates...')
            
            # Seed role templates for each role
            self.seed_admin_role()
            self.seed_team_leader_role()
            self.seed_loan_officer_role()
            self.seed_secretary_role()
            self.seed_auditor_role()

        self.stdout.write(
            self.style.SUCCESS('Successfully seeded all role permission templates')
        )

    def create_role_permission(self, role, permission_code, is_allowed=True, can_override=True):
        """Helper method to create a role permission template"""
        try:
            page_name, action_code = permission_code.split('.', 1)
            permission = PagePermission.objects.get(page_name=page_name, action_code=action_code)
            
            template, created = RolePermissionTemplate.objects.get_or_create(
                role=role,
                page_permission=permission,
                defaults={
                    'is_allowed': is_allowed,
                    'can_override': can_override,
                }
            )
            if created:
                status = "✓" if is_allowed else "✗"
                self.stdout.write(f'    {role}: {permission_code} {status}')
            return template
        except PagePermission.DoesNotExist:
            self.stdout.write(
                self.style.WARNING(f'Permission not found: {permission_code}')
            )
            return None

    def seed_admin_role(self):
        """Seed permissions for admin role - full access to everything"""
        self.stdout.write('  Seeding admin role permissions...')
        
        # Get all permissions and grant them to admin
        all_permissions = PagePermission.objects.all()
        for permission in all_permissions:
            permission_code = f"{permission.page_name}.{permission.action_code}"
            self.create_role_permission('admin', permission_code, is_allowed=True, can_override=False)

    def seed_team_leader_role(self):
        """Seed permissions for team leader role - management and oversight"""
        self.stdout.write('  Seeding team leader role permissions...')
        
        # Dashboard permissions
        dashboard_permissions = [
            'dashboard.view_overview', 'dashboard.view_loan_metrics', 'dashboard.view_client_metrics',
            'dashboard.view_financial_summary', 'dashboard.view_portfolio_performance',
            'dashboard.view_collection_status', 'dashboard.view_alerts', 'dashboard.view_quick_actions',
            'dashboard.customize_layout', 'dashboard.export_dashboard'
        ]
        
        # Loans permissions - full access except critical modifications
        loans_permissions = [
            'loans.view_applications', 'loans.view_active', 'loans.view_defaulted', 'loans.view_calculations',
            'loans.create_application', 'loans.edit_application', 'loans.approve_application',
            'loans.reject_application', 'loans.process_rollover', 'loans.mark_complete',
            'loans.generate_reports', 'loans.export_data'
        ]
        
        # Clients permissions - full access
        clients_permissions = [
            'clients.view_list', 'clients.view_history', 'clients.view_pending', 'clients.view_rejected',
            'clients.create_new', 'clients.edit_info', 'clients.manage_documents', 'clients.assign_manager',
            'clients.approve_client', 'clients.reject_client', 'clients.export_data', 'clients.generate_reports'
        ]
        
        # Reports permissions - full access
        reports_permissions = [
            'reports.view_dashboard', 'reports.loan_performance', 'reports.client_analytics',
            'reports.portfolio_summary', 'reports.financial_statements', 'reports.collection_reports',
            'reports.branch_performance', 'reports.officer_performance', 'reports.custom_reports',
            'reports.export_pdf', 'reports.export_excel', 'reports.export_csv',
            'reports.schedule_reports', 'reports.share_reports', 'reports.manage_templates'
        ]
        
        # Repayments permissions - full access
        repayments_permissions = [
            'repayments.view_payments', 'repayments.view_outstanding', 'repayments.view_overdue',
            'repayments.record_payment', 'repayments.generate_receipts', 'repayments.export_payment_data'
        ]
        
        # Documents permissions - full access
        documents_permissions = [
            'documents.view_documents', 'documents.view_templates', 'documents.upload_documents',
            'documents.create_templates', 'documents.edit_documents', 'documents.manage_categories',
            'documents.approve_documents'
        ]
        
        # Settings permissions - limited access
        settings_permissions = [
            'settings.view_system_settings', 'settings.view_user_management', 'settings.view_branch_settings',
            'settings.view_loan_settings', 'settings.edit_branch_settings', 'settings.manage_users'
        ]
        
        all_permissions = (dashboard_permissions + loans_permissions + clients_permissions + 
                          reports_permissions + repayments_permissions + documents_permissions + 
                          settings_permissions)
        
        for permission in all_permissions:
            self.create_role_permission('team_leader', permission)

    def seed_loan_officer_role(self):
        """Seed permissions for loan officer role - client and loan management"""
        self.stdout.write('  Seeding loan officer role permissions...')
        
        # Dashboard permissions - basic access
        dashboard_permissions = [
            'dashboard.view_overview', 'dashboard.view_loan_metrics', 'dashboard.view_client_metrics',
            'dashboard.view_portfolio_performance', 'dashboard.view_collection_status',
            'dashboard.view_quick_actions', 'dashboard.customize_layout'
        ]
        
        # Loans permissions - operational access
        loans_permissions = [
            'loans.view_applications', 'loans.view_active', 'loans.view_calculations',
            'loans.create_application', 'loans.edit_application', 'loans.mark_complete',
            'loans.generate_reports', 'loans.export_data'
        ]
        
        # Clients permissions - full operational access
        clients_permissions = [
            'clients.view_list', 'clients.view_history', 'clients.view_pending',
            'clients.create_new', 'clients.edit_info', 'clients.manage_documents',
            'clients.export_data', 'clients.generate_reports'
        ]
        
        # Reports permissions - portfolio focused
        reports_permissions = [
            'reports.view_dashboard', 'reports.loan_performance', 'reports.client_analytics',
            'reports.portfolio_summary', 'reports.collection_reports', 'reports.export_pdf',
            'reports.export_excel', 'reports.export_csv'
        ]
        
        # Repayments permissions - full operational access
        repayments_permissions = [
            'repayments.view_payments', 'repayments.view_outstanding', 'repayments.view_overdue',
            'repayments.record_payment', 'repayments.generate_receipts', 'repayments.export_payment_data'
        ]
        
        # Documents permissions - operational access
        documents_permissions = [
            'documents.view_documents', 'documents.view_templates', 'documents.upload_documents',
            'documents.edit_documents'
        ]
        
        all_permissions = (dashboard_permissions + loans_permissions + clients_permissions + 
                          reports_permissions + repayments_permissions + documents_permissions)
        
        for permission in all_permissions:
            self.create_role_permission('loan_officer', permission)

    def seed_secretary_role(self):
        """Seed permissions for secretary role - data entry and basic operations"""
        self.stdout.write('  Seeding secretary role permissions...')
        
        # Dashboard permissions - basic view
        dashboard_permissions = [
            'dashboard.view_overview', 'dashboard.view_client_metrics', 'dashboard.view_quick_actions'
        ]
        
        # Loans permissions - view and basic operations
        loans_permissions = [
            'loans.view_applications', 'loans.view_active', 'loans.create_application',
            'loans.edit_application', 'loans.export_data'
        ]
        
        # Clients permissions - data entry focused
        clients_permissions = [
            'clients.view_list', 'clients.view_history', 'clients.create_new',
            'clients.edit_info', 'clients.manage_documents', 'clients.export_data'
        ]
        
        # Reports permissions - basic access
        reports_permissions = [
            'reports.view_dashboard', 'reports.client_analytics', 'reports.export_pdf',
            'reports.export_excel', 'reports.export_csv'
        ]
        
        # Repayments permissions - basic operations
        repayments_permissions = [
            'repayments.view_payments', 'repayments.view_outstanding',
            'repayments.record_payment', 'repayments.generate_receipts'
        ]
        
        # Documents permissions - full access for document management
        documents_permissions = [
            'documents.view_documents', 'documents.view_templates', 'documents.upload_documents',
            'documents.edit_documents', 'documents.manage_categories'
        ]
        
        all_permissions = (dashboard_permissions + loans_permissions + clients_permissions + 
                          reports_permissions + repayments_permissions + documents_permissions)
        
        for permission in all_permissions:
            self.create_role_permission('secretary', permission)

    def seed_auditor_role(self):
        """Seed permissions for auditor role - read-only access with comprehensive reporting"""
        self.stdout.write('  Seeding auditor role permissions...')
        
        # Dashboard permissions - full view access
        dashboard_permissions = [
            'dashboard.view_overview', 'dashboard.view_loan_metrics', 'dashboard.view_client_metrics',
            'dashboard.view_financial_summary', 'dashboard.view_portfolio_performance',
            'dashboard.view_collection_status', 'dashboard.view_alerts', 'dashboard.export_dashboard'
        ]
        
        # Loans permissions - view only
        loans_permissions = [
            'loans.view_applications', 'loans.view_active', 'loans.view_defaulted',
            'loans.view_calculations', 'loans.generate_reports', 'loans.export_data'
        ]
        
        # Clients permissions - view and export only
        clients_permissions = [
            'clients.view_list', 'clients.view_history', 'clients.view_pending',
            'clients.view_rejected', 'clients.export_data', 'clients.generate_reports'
        ]
        
        # Reports permissions - full access to all reports
        reports_permissions = [
            'reports.view_dashboard', 'reports.loan_performance', 'reports.client_analytics',
            'reports.portfolio_summary', 'reports.financial_statements', 'reports.regulatory_reports',
            'reports.collection_reports', 'reports.branch_performance', 'reports.officer_performance',
            'reports.custom_reports', 'reports.export_pdf', 'reports.export_excel',
            'reports.export_csv', 'reports.schedule_reports', 'reports.share_reports'
        ]
        
        # Repayments permissions - view and export only
        repayments_permissions = [
            'repayments.view_payments', 'repayments.view_outstanding', 'repayments.view_overdue',
            'repayments.export_payment_data'
        ]
        
        # Documents permissions - view only
        documents_permissions = [
            'documents.view_documents', 'documents.view_templates'
        ]
        
        # Settings permissions - view only
        settings_permissions = [
            'settings.view_system_settings', 'settings.view_user_management',
            'settings.view_branch_settings', 'settings.view_loan_settings'
        ]
        
        all_permissions = (dashboard_permissions + loans_permissions + clients_permissions + 
                          reports_permissions + repayments_permissions + documents_permissions +
                          settings_permissions)
        
        for permission in all_permissions:
            # Auditors can't override their permissions (compliance requirement)
            self.create_role_permission('auditor', permission, can_override=False)