
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta
from customers.models import CustomerActionLog, Customer
from django.db.models import Count
import csv

class Command(BaseCommand):
    help = 'Generate customer action audit report'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--days',
            type=int,
            default=30,
            help='Number of days to look back (default: 30)',
        )
        parser.add_argument(
            '--customer-id',
            type=str,
            help='Specific customer ID to audit',
        )
        parser.add_argument(
            '--export-csv',
            action='store_true',
            help='Export results to CSV file',
        )
        parser.add_argument(
            '--action-type',
            type=str,
            help='Filter by specific action type',
        )
    
    def handle(self, *args, **options):
        days = options['days']
        customer_id = options.get('customer_id')
        export_csv = options['export_csv']
        action_type = options.get('action_type')
        
        # Calculate date range
        end_date = timezone.now()
        start_date = end_date - timedelta(days=days)
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Customer Action Audit Report ({start_date.date()} to {end_date.date()})'
            )
        )
        
        # Build query
        queryset = CustomerActionLog.objects.filter(
            created_at__range=[start_date, end_date]
        )
        
        if customer_id:
            try:
                customer = Customer.objects.get(customer_id=customer_id)
                queryset = queryset.filter(customer=customer)
                self.stdout.write(f'Filtering for customer: {customer_id}')
            except Customer.DoesNotExist:
                self.stdout.write(self.style.ERROR(f'Customer {customer_id} not found'))
                return
        
        if action_type:
            queryset = queryset.filter(action_type=action_type)
            self.stdout.write(f'Filtering for action type: {action_type}')
        
        # Get statistics
        total_actions = queryset.count()
        
        # Action type breakdown
        action_breakdown = queryset.values('action_type').annotate(
            count=Count('id')
        ).order_by('-count')
        
        # User breakdown
        user_breakdown = queryset.exclude(performed_by=None).values(
            'performed_by__username', 'performed_by__first_name', 'performed_by__last_name'
        ).annotate(count=Count('id')).order_by('-count')
        
        # System vs manual actions
        system_actions = queryset.filter(system_action=True).count()
        manual_actions = queryset.filter(system_action=False).count()
        
        # Display results
        self.stdout.write(f'\nTotal Actions: {total_actions}')
        self.stdout.write(f'System Actions: {system_actions}')
        self.stdout.write(f'Manual Actions: {manual_actions}')
        
        self.stdout.write('\nAction Type Breakdown:')
        for action in action_breakdown:
            self.stdout.write(f'  {action["action_type"]}: {action["count"]}')
        
        self.stdout.write('\nTop Users by Actions:')
        for user in user_breakdown[:10]:
            name = f"{user['performed_by__first_name']} {user['performed_by__last_name']}".strip()
            if not name:
                name = user['performed_by__username']
            self.stdout.write(f'  {name}: {user["count"]}')
        
        # Export to CSV if requested
        if export_csv:
            filename = f'customer_audit_{start_date.date()}_{end_date.date()}.csv'
            
            with open(filename, 'w', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([
                    'Customer ID', 'Action Type', 'Description', 'Performed By',
                    'System Action', 'IP Address', 'Date/Time', 'Reference ID'
                ])
                
                for log in queryset.select_related('customer', 'performed_by'):
                    performer = log.performed_by.get_full_name() if log.performed_by else 'System'
                    writer.writerow([
                        log.customer.customer_id,
                        log.action_type,
                        log.description,
                        performer,
                        'Yes' if log.system_action else 'No',
                        log.ip_address or '',
                        log.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                        log.reference_id or ''
                    ])
            
            self.stdout.write(self.style.SUCCESS(f'Report exported to {filename}'))
