"""
Management command to seed granular page-specific permissions
"""
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 granular page-specific permissions for all pages'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing permissions before seeding',
        )

    def handle(self, *args, **options):
        if options['clear']:
            self.stdout.write('Clearing existing permissions...')
            PagePermission.objects.all().delete()
            RolePermissionTemplate.objects.all().delete()

        with transaction.atomic():
            self.stdout.write('Seeding page permissions...')
            
            # Seed loans page permissions
            self.seed_loans_permissions()
            
            # Seed clients page permissions
            self.seed_clients_permissions()
            
            # Seed reports page permissions
            self.seed_reports_permissions()
            
            # Seed dashboard and other page permissions
            self.seed_dashboard_permissions()
            self.seed_repayments_permissions()
            self.seed_documents_permissions()
            self.seed_settings_permissions()

        self.stdout.write(
            self.style.SUCCESS('Successfully seeded all page permissions')
        )

    def create_permission(self, page_name, action_code, action_name, description, category, is_critical=False):
        """Helper method to create a permission"""
        permission, created = PagePermission.objects.get_or_create(
            page_name=page_name,
            action_code=action_code,
            defaults={
                'action_name': action_name,
                'description': description,
                'category': category,
                'is_critical': is_critical,
            }
        )
        if created:
            self.stdout.write(f'  Created: {page_name}.{action_code}')
        return permission

    def seed_loans_permissions(self):
        """Seed permissions for loans page"""
        self.stdout.write('  Seeding loans page permissions...')
        
        # View permissions
        self.create_permission(
            'loans', 'view_applications', 'View Loan Applications',
            'View and browse loan applications', 'view'
        )
        self.create_permission(
            'loans', 'view_active', 'View Active Loans',
            'View active loan details and status', 'view'
        )
        self.create_permission(
            'loans', 'view_defaulted', 'View Defaulted Loans',
            'View loans that are in default status', 'view'
        )
        self.create_permission(
            'loans', 'view_calculations', 'View Loan Calculations',
            'View loan interest calculations and payment schedules', 'view'
        )
        
        # Create permissions
        self.create_permission(
            'loans', 'create_application', 'Create Loan Application',
            'Create new loan applications for clients', 'create'
        )
        
        # Edit permissions
        self.create_permission(
            'loans', 'edit_application', 'Edit Loan Application',
            'Edit existing loan applications before approval', 'edit'
        )
        self.create_permission(
            'loans', 'edit_terms', 'Edit Loan Terms',
            'Modify loan terms and conditions', 'edit', is_critical=True
        )
        self.create_permission(
            'loans', 'modify_interest', 'Modify Interest Rates',
            'Change interest rates on loans', 'edit', is_critical=True
        )
        
        # Delete permissions
        self.create_permission(
            'loans', 'delete_application', 'Delete Loan Application',
            'Delete loan applications', 'delete', is_critical=True
        )
        
        # Approval permissions
        self.create_permission(
            'loans', 'approve_application', 'Approve Loan Application',
            'Approve loan applications for disbursement', 'approve', is_critical=True
        )
        self.create_permission(
            'loans', 'reject_application', 'Reject Loan Application',
            'Reject loan applications with reasons', 'approve'
        )
        
        # Process permissions
        self.create_permission(
            'loans', 'process_rollover', 'Process Loan Rollover',
            'Process loan rollovers and extensions', 'process', is_critical=True
        )
        self.create_permission(
            'loans', 'mark_complete', 'Mark Loan Complete',
            'Mark loans as completed when fully paid', 'process'
        )
        
        # Export permissions
        self.create_permission(
            'loans', 'generate_reports', 'Generate Loan Reports',
            'Generate various loan reports and analytics', 'export'
        )
        self.create_permission(
            'loans', 'export_data', 'Export Loan Data',
            'Export loan data to Excel, PDF, or CSV formats', 'export'
        )

    def seed_clients_permissions(self):
        """Seed permissions for clients page"""
        self.stdout.write('  Seeding clients page permissions...')
        
        # View permissions
        self.create_permission(
            'clients', 'view_list', 'View Client List',
            'View the list of all clients', 'view'
        )
        self.create_permission(
            'clients', 'view_history', 'View Client Loan History',
            'View client loan history and past transactions', 'view'
        )
        self.create_permission(
            'clients', 'view_pending', 'View Pending Client Approvals',
            'View clients pending approval', 'view'
        )
        self.create_permission(
            'clients', 'view_rejected', 'View Rejected Clients',
            'View clients that have been rejected', 'view'
        )
        
        # Create permissions
        self.create_permission(
            'clients', 'create_new', 'Add New Client',
            'Add new clients to the system', 'create'
        )
        
        # Edit permissions
        self.create_permission(
            'clients', 'edit_info', 'Edit Client Information',
            'Edit client personal and business information', 'edit'
        )
        
        # Delete permissions
        self.create_permission(
            'clients', 'delete_client', 'Delete Client',
            'Delete client records from the system', 'delete', is_critical=True
        )
        
        # Manage permissions
        self.create_permission(
            'clients', 'manage_documents', 'Manage Client Documents',
            'Upload, view, and manage client documents', 'manage'
        )
        self.create_permission(
            'clients', 'assign_manager', 'Assign Portfolio Manager',
            'Assign or change client portfolio manager', 'manage'
        )
        
        # Approval permissions
        self.create_permission(
            'clients', 'approve_client', 'Approve Client Application',
            'Approve new client applications', 'approve', is_critical=True
        )
        self.create_permission(
            'clients', 'reject_client', 'Reject Client Application',
            'Reject client applications with reasons', 'approve'
        )
        
        # Export permissions
        self.create_permission(
            'clients', 'export_data', 'Export Client Data',
            'Export client data to various formats', 'export'
        )
        self.create_permission(
            'clients', 'generate_reports', 'Generate Client Reports',
            'Generate client analytics and reports', 'export'
        )

    def seed_reports_permissions(self):
        """Seed permissions for reports page"""
        self.stdout.write('  Seeding reports page permissions...')
        
        # View permissions for different report categories
        self.create_permission(
            'reports', 'view_dashboard', 'View Reports Dashboard',
            'Access the main reports dashboard', 'view'
        )
        self.create_permission(
            'reports', 'loan_performance', 'Access Loan Performance Reports',
            'View loan performance and analytics reports', 'view'
        )
        self.create_permission(
            'reports', 'client_analytics', 'Access Client Analytics',
            'View client analytics and demographic reports', 'view'
        )
        self.create_permission(
            'reports', 'portfolio_summary', 'Access Portfolio Summary Reports',
            'View portfolio summary and performance reports', 'view'
        )
        self.create_permission(
            'reports', 'financial_statements', 'Access Financial Statements',
            'View financial statements and accounting reports', 'view', is_critical=True
        )
        self.create_permission(
            'reports', 'regulatory_reports', 'Access Regulatory Reports',
            'View regulatory compliance and audit reports', 'view', is_critical=True
        )
        self.create_permission(
            'reports', 'collection_reports', 'Access Collection Reports',
            'View collection performance and overdue reports', 'view'
        )
        self.create_permission(
            'reports', 'branch_performance', 'Access Branch Performance Reports',
            'View branch-wise performance and comparison reports', 'view'
        )
        self.create_permission(
            'reports', 'officer_performance', 'Access Officer Performance Reports',
            'View loan officer performance and productivity reports', 'view'
        )
        
        # Create permissions
        self.create_permission(
            'reports', 'custom_reports', 'Create Custom Reports',
            'Create and save custom report configurations', 'create'
        )
        
        # Export permissions
        self.create_permission(
            'reports', 'export_pdf', 'Export Reports as PDF',
            'Export reports in PDF format', 'export'
        )
        self.create_permission(
            'reports', 'export_excel', 'Export Reports as Excel',
            'Export reports in Excel format', 'export'
        )
        self.create_permission(
            'reports', 'export_csv', 'Export Reports as CSV',
            'Export reports in CSV format', 'export'
        )
        
        # Manage permissions
        self.create_permission(
            'reports', 'schedule_reports', 'Schedule Automated Reports',
            'Schedule reports for automatic generation and delivery', 'manage'
        )
        self.create_permission(
            'reports', 'share_reports', 'Share Reports',
            'Share reports with other users or external parties', 'manage'
        )
        self.create_permission(
            'reports', 'manage_templates', 'Manage Report Templates',
            'Create and modify report templates', 'manage'
        )

    def seed_dashboard_permissions(self):
        """Seed permissions for dashboard page"""
        self.stdout.write('  Seeding dashboard page permissions...')
        
        # View permissions for different dashboard widgets
        self.create_permission(
            'dashboard', 'view_overview', 'View Dashboard Overview',
            'Access the main dashboard overview', 'view'
        )
        self.create_permission(
            'dashboard', 'view_loan_metrics', 'View Loan Metrics Widget',
            'View loan performance metrics on dashboard', 'view'
        )
        self.create_permission(
            'dashboard', 'view_client_metrics', 'View Client Metrics Widget',
            'View client statistics and growth metrics', 'view'
        )
        self.create_permission(
            'dashboard', 'view_financial_summary', 'View Financial Summary Widget',
            'View financial summary and revenue metrics', 'view'
        )
        self.create_permission(
            'dashboard', 'view_portfolio_performance', 'View Portfolio Performance Widget',
            'View portfolio performance charts and metrics', 'view'
        )
        self.create_permission(
            'dashboard', 'view_collection_status', 'View Collection Status Widget',
            'View collection status and overdue metrics', 'view'
        )
        self.create_permission(
            'dashboard', 'view_alerts', 'View System Alerts',
            'View system alerts and notifications on dashboard', 'view'
        )
        self.create_permission(
            'dashboard', 'view_quick_actions', 'View Quick Actions',
            'Access quick action buttons on dashboard', 'view'
        )
        
        # Manage permissions
        self.create_permission(
            'dashboard', 'customize_layout', 'Customize Dashboard Layout',
            'Customize dashboard widget layout and preferences', 'manage'
        )
        self.create_permission(
            'dashboard', 'export_dashboard', 'Export Dashboard Data',
            'Export dashboard data and charts', 'export'
        )

    def seed_repayments_permissions(self):
        """Seed permissions for repayments page"""
        self.stdout.write('  Seeding repayments page permissions...')
        
        # View permissions
        self.create_permission(
            'repayments', 'view_payments', 'View Payment Records',
            'View payment history and records', 'view'
        )
        self.create_permission(
            'repayments', 'view_outstanding', 'View Outstanding Balances',
            'View outstanding loan balances and due amounts', 'view'
        )
        self.create_permission(
            'repayments', 'view_overdue', 'View Overdue Payments',
            'View overdue payments and collection status', 'view'
        )
        
        # Create permissions
        self.create_permission(
            'repayments', 'record_payment', 'Record Payment',
            'Record new loan payments and repayments', 'create'
        )
        
        # Process permissions
        self.create_permission(
            'repayments', 'process_refund', 'Process Refunds',
            'Process payment refunds and adjustments', 'process', is_critical=True
        )
        self.create_permission(
            'repayments', 'reverse_payment', 'Reverse Payment',
            'Reverse incorrect or duplicate payments', 'process', is_critical=True
        )
        
        # Export permissions
        self.create_permission(
            'repayments', 'generate_receipts', 'Generate Payment Receipts',
            'Generate and print payment receipts', 'export'
        )
        self.create_permission(
            'repayments', 'export_payment_data', 'Export Payment Data',
            'Export payment data to various formats', 'export'
        )

    def seed_documents_permissions(self):
        """Seed permissions for documents page"""
        self.stdout.write('  Seeding documents page permissions...')
        
        # View permissions
        self.create_permission(
            'documents', 'view_documents', 'View Documents',
            'View uploaded documents and files', 'view'
        )
        self.create_permission(
            'documents', 'view_templates', 'View Document Templates',
            'View available document templates', 'view'
        )
        
        # Create permissions
        self.create_permission(
            'documents', 'upload_documents', 'Upload Documents',
            'Upload new documents and files', 'create'
        )
        self.create_permission(
            'documents', 'create_templates', 'Create Document Templates',
            'Create new document templates', 'create'
        )
        
        # Edit permissions
        self.create_permission(
            'documents', 'edit_documents', 'Edit Document Information',
            'Edit document metadata and information', 'edit'
        )
        
        # Delete permissions
        self.create_permission(
            'documents', 'delete_documents', 'Delete Documents',
            'Delete documents and files', 'delete', is_critical=True
        )
        
        # Manage permissions
        self.create_permission(
            'documents', 'manage_categories', 'Manage Document Categories',
            'Create and manage document categories', 'manage'
        )
        self.create_permission(
            'documents', 'approve_documents', 'Approve Documents',
            'Approve uploaded documents for official use', 'approve'
        )

    def seed_settings_permissions(self):
        """Seed permissions for settings and administration pages"""
        self.stdout.write('  Seeding settings page permissions...')
        
        # View permissions
        self.create_permission(
            'settings', 'view_system_settings', 'View System Settings',
            'View system configuration and settings', 'view'
        )
        self.create_permission(
            'settings', 'view_user_management', 'View User Management',
            'View user accounts and role assignments', 'view'
        )
        self.create_permission(
            'settings', 'view_branch_settings', 'View Branch Settings',
            'View branch configuration and settings', 'view'
        )
        self.create_permission(
            'settings', 'view_loan_settings', 'View Loan Settings',
            'View loan product configuration and interest rates', 'view'
        )
        
        # Edit permissions
        self.create_permission(
            'settings', 'edit_system_settings', 'Edit System Settings',
            'Modify system configuration and settings', 'edit', is_critical=True
        )
        self.create_permission(
            'settings', 'edit_loan_settings', 'Edit Loan Settings',
            'Modify loan products and interest rate settings', 'edit', is_critical=True
        )
        self.create_permission(
            'settings', 'edit_branch_settings', 'Edit Branch Settings',
            'Modify branch configuration and settings', 'edit'
        )
        
        # Manage permissions
        self.create_permission(
            'settings', 'manage_users', 'Manage User Accounts',
            'Create, edit, and deactivate user accounts', 'manage', is_critical=True
        )
        self.create_permission(
            'settings', 'manage_permissions', 'Manage User Permissions',
            'Assign and modify user permissions and roles', 'manage', is_critical=True
        )
        self.create_permission(
            'settings', 'manage_branches', 'Manage Branches',
            'Create and manage branch locations', 'manage'
        )
        self.create_permission(
            'settings', 'backup_restore', 'Backup and Restore',
            'Perform system backup and restore operations', 'manage', is_critical=True
        )