"""
Management command to set up audit integration with existing views
"""
from django.core.management.base import BaseCommand
from django.conf import settings
import os
import re


class Command(BaseCommand):
    help = 'Set up audit integration with existing views'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be done without making changes',
        )
    
    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        self.stdout.write(self.style.SUCCESS('Setting up audit integration...'))
        
        # Add middleware to settings
        self._add_audit_middleware(dry_run)
        
        # Update key views with audit decorators
        self._update_views_with_audit(dry_run)
        
        # Create audit dashboard views
        self._create_audit_views(dry_run)
        
        self.stdout.write(self.style.SUCCESS('Audit integration setup complete!'))
    
    def _add_audit_middleware(self, dry_run):
        """Add audit middleware to Django settings"""
        self.stdout.write('Adding audit middleware to settings...')
        
        middleware_to_add = [
            'users.audit_middleware.AuditMiddleware',
            'users.audit_middleware.PermissionAuditMiddleware',
            'users.audit_middleware.ThreadLocalUserMiddleware',
        ]
        
        if dry_run:
            self.stdout.write(f'Would add middleware: {middleware_to_add}')
        else:
            self.stdout.write(self.style.WARNING(
                'Please manually add the following middleware to your MIDDLEWARE setting in settings.py:'
            ))
            for middleware in middleware_to_add:
                self.stdout.write(f'  "{middleware}",')
    
    def _update_views_with_audit(self, dry_run):
        """Update key views with audit decorators"""
        self.stdout.write('Updating views with audit decorators...')
        
        # Define views that should have audit logging
        views_to_update = [
            {
                'file': 'users/views.py',
                'functions': [
                    'user_permissions_view',
                    'update_user_permissions',
                    'create_user',
                    'delete_user',
                ],
                'decorator': '@audit_action(module="users")'
            },
            {
                'file': 'loans/views.py',
                'functions': [
                    'create_loan',
                    'approve_loan',
                    'delete_loan',
                ],
                'decorator': '@audit_data_modification()'
            },
            {
                'file': 'reports/views.py',
                'functions': [
                    'export_pdf',
                    'export_excel',
                    'generate_report',
                ],
                'decorator': '@audit_export_action()'
            }
        ]
        
        for view_config in views_to_update:
            if dry_run:
                self.stdout.write(f'Would update {view_config["file"]} with audit decorators')
            else:
                self._add_decorators_to_file(view_config)
    
    def _add_decorators_to_file(self, view_config):
        """Add audit decorators to a specific file"""
        file_path = view_config['file']
        
        if not os.path.exists(file_path):
            self.stdout.write(f'File {file_path} not found, skipping...')
            return
        
        try:
            with open(file_path, 'r') as f:
                content = f.read()
            
            # Add import for audit decorators at the top
            if 'from users.audit_decorators import' not in content:
                import_line = 'from users.audit_decorators import audit_action, audit_data_modification, audit_export_action\n'
                
                # Find the last import line
                lines = content.split('\n')
                last_import_index = 0
                for i, line in enumerate(lines):
                    if line.startswith('from ') or line.startswith('import '):
                        last_import_index = i
                
                lines.insert(last_import_index + 1, import_line)
                content = '\n'.join(lines)
            
            # Add decorators to specified functions
            for function_name in view_config['functions']:
                pattern = rf'(def {function_name}\([^)]*\):)'
                if re.search(pattern, content):
                    replacement = f'{view_config["decorator"]}\n\\1'
                    content = re.sub(pattern, replacement, content)
            
            # Write back to file
            with open(file_path, 'w') as f:
                f.write(content)
            
            self.stdout.write(f'Updated {file_path} with audit decorators')
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error updating {file_path}: {e}'))
    
    def _create_audit_views(self, dry_run):
        """Create audit dashboard views"""
        self.stdout.write('Creating audit dashboard views...')
        
        audit_views_content = '''"""
Audit dashboard views for monitoring user activities and security events
"""
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Count, Q
from django.utils import timezone
from datetime import timedelta
from .models import EnhancedAuditLog, SecurityAlert, DataAccessPattern, PermissionChangeLog
from .audit_service import audit_service
from .audit_decorators import audit_action


@staff_member_required
@audit_action(action='view_audit_dashboard', module='audit')
def audit_dashboard(request):
    """Main audit dashboard"""
    # Get recent security alerts
    recent_alerts = SecurityAlert.objects.filter(
        is_resolved=False
    ).order_by('-created_at')[:10]
    
    # Get recent audit events
    recent_events = EnhancedAuditLog.objects.filter(
        is_security_event=True
    ).order_by('-timestamp')[:20]
    
    # Get user activity summary
    today = timezone.now().date()
    week_ago = today - timedelta(days=7)
    
    activity_stats = {
        'total_events_today': EnhancedAuditLog.objects.filter(
            timestamp__date=today
        ).count(),
        'security_events_week': EnhancedAuditLog.objects.filter(
            timestamp__date__gte=week_ago,
            is_security_event=True
        ).count(),
        'permission_denials_week': EnhancedAuditLog.objects.filter(
            timestamp__date__gte=week_ago,
            permission_granted=False
        ).count(),
        'active_alerts': SecurityAlert.objects.filter(
            is_resolved=False
        ).count(),
    }
    
    context = {
        'recent_alerts': recent_alerts,
        'recent_events': recent_events,
        'activity_stats': activity_stats,
    }
    
    return render(request, 'users/audit_dashboard.html', context)


@staff_member_required
@audit_action(action='view_audit_logs', module='audit')
def audit_logs(request):
    """View detailed audit logs with filtering"""
    # Get filter parameters
    user_id = request.GET.get('user')
    event_type = request.GET.get('event_type')
    module = request.GET.get('module')
    date_from = request.GET.get('date_from')
    date_to = request.GET.get('date_to')
    
    # Build query
    logs = EnhancedAuditLog.objects.select_related('user').all()
    
    if user_id:
        logs = logs.filter(user_id=user_id)
    if event_type:
        logs = logs.filter(event_type=event_type)
    if module:
        logs = logs.filter(module=module)
    if date_from:
        logs = logs.filter(timestamp__date__gte=date_from)
    if date_to:
        logs = logs.filter(timestamp__date__lte=date_to)
    
    # Paginate results
    paginator = Paginator(logs, 50)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # Get filter options
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    context = {
        'page_obj': page_obj,
        'users': User.objects.filter(is_active=True).order_by('username'),
        'event_types': EnhancedAuditLog.objects.values_list('event_type', flat=True).distinct(),
        'modules': EnhancedAuditLog.objects.values_list('module', flat=True).distinct(),
        'filters': {
            'user': user_id,
            'event_type': event_type,
            'module': module,
            'date_from': date_from,
            'date_to': date_to,
        }
    }
    
    return render(request, 'users/audit_logs.html', context)


@staff_member_required
@audit_action(action='view_security_alerts', module='audit')
def security_alerts(request):
    """View and manage security alerts"""
    # Get filter parameters
    severity = request.GET.get('severity')
    resolved = request.GET.get('resolved')
    
    alerts = SecurityAlert.objects.select_related('user', 'resolved_by').all()
    
    if severity:
        alerts = alerts.filter(severity=severity)
    if resolved is not None:
        alerts = alerts.filter(is_resolved=resolved == 'true')
    
    # Paginate results
    paginator = Paginator(alerts, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'severities': SecurityAlert.objects.values_list('severity', flat=True).distinct(),
        'filters': {
            'severity': severity,
            'resolved': resolved,
        }
    }
    
    return render(request, 'users/security_alerts.html', context)


@staff_member_required
@audit_action(action='resolve_security_alert', module='audit')
def resolve_alert(request, alert_id):
    """Resolve a security alert"""
    if request.method == 'POST':
        try:
            alert = SecurityAlert.objects.get(id=alert_id)
            resolution_notes = request.POST.get('resolution_notes', '')
            
            alert.resolve(resolved_by=request.user, notes=resolution_notes)
            
            return JsonResponse({'success': True})
        except SecurityAlert.DoesNotExist:
            return JsonResponse({'success': False, 'error': 'Alert not found'})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})


@staff_member_required
@audit_action(action='view_user_activity', module='audit')
def user_activity_report(request, user_id):
    """Detailed activity report for a specific user"""
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        return render(request, '404.html')
    
    # Get activity summary
    days = int(request.GET.get('days', 30))
    activity_summary = audit_service.get_user_activity_summary(user, days)
    
    # Get recent activities
    recent_activities = EnhancedAuditLog.objects.filter(
        user=user
    ).order_by('-timestamp')[:50]
    
    # Get access patterns
    access_patterns = DataAccessPattern.objects.filter(
        user=user
    ).order_by('-date')[:30]
    
    # Get permission changes
    permission_changes = PermissionChangeLog.objects.filter(
        user=user
    ).order_by('-timestamp')[:20]
    
    context = {
        'target_user': user,
        'activity_summary': activity_summary,
        'recent_activities': recent_activities,
        'access_patterns': access_patterns,
        'permission_changes': permission_changes,
        'days': days,
    }
    
    return render(request, 'users/user_activity_report.html', context)


@staff_member_required
@audit_action(action='view_anomaly_detection', module='audit')
def anomaly_detection(request):
    """View detected anomalies in user behavior"""
    days = int(request.GET.get('days', 7))
    anomalies = audit_service.detect_anomalies(days=days)
    
    context = {
        'anomalies': anomalies,
        'days': days,
    }
    
    return render(request, 'users/anomaly_detection.html', context)
'''
        
        if dry_run:
            self.stdout.write('Would create audit views file')
        else:
            with open('users/audit_views.py', 'w') as f:
                f.write(audit_views_content)
            self.stdout.write('Created users/audit_views.py')
        
        # Create URL patterns
        url_patterns = '''"""
URL patterns for audit dashboard
"""
from django.urls import path
from . import audit_views

app_name = 'audit'

urlpatterns = [
    path('dashboard/', audit_views.audit_dashboard, name='dashboard'),
    path('logs/', audit_views.audit_logs, name='logs'),
    path('alerts/', audit_views.security_alerts, name='alerts'),
    path('alerts/<uuid:alert_id>/resolve/', audit_views.resolve_alert, name='resolve_alert'),
    path('user/<uuid:user_id>/activity/', audit_views.user_activity_report, name='user_activity'),
    path('anomalies/', audit_views.anomaly_detection, name='anomalies'),
]
'''
        
        if dry_run:
            self.stdout.write('Would create audit URLs file')
        else:
            with open('users/audit_urls.py', 'w') as f:
                f.write(url_patterns)
            self.stdout.write('Created users/audit_urls.py')
            
            self.stdout.write(self.style.WARNING(
                'Please add the following to your main urls.py:'
            ))
            self.stdout.write('  path("audit/", include("users.audit_urls")),')