from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from users.models import CustomUser
from users.views import get_client_dependencies, safe_delete_client_permanently
from utils.models import AuditLog
import sys


class Command(BaseCommand):
    help = 'Safely delete clients with comprehensive dependency handling'

    def add_arguments(self, parser):
        parser.add_argument(
            'client_ids',
            nargs='*',
            type=str,
            help='Client IDs to delete (space-separated)'
        )
        parser.add_argument(
            '--mode',
            choices=['blacklist', 'permanent'],
            default='blacklist',
            help='Deletion mode: blacklist (soft delete) or permanent (hard delete)'
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be deleted without actually deleting'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Skip confirmation prompts'
        )
        parser.add_argument(
            '--status',
            choices=['active', 'suspended', 'blacklisted', 'all'],
            default='all',
            help='Filter clients by status before deletion'
        )
        parser.add_argument(
            '--bulk-file',
            type=str,
            help='Path to file containing client IDs (one per line)'
        )

    def handle(self, *args, **options):
        client_ids = options['client_ids']
        mode = options['mode']
        dry_run = options['dry_run']
        force = options['force']
        status_filter = options['status']
        bulk_file = options['bulk_file']

        # Get client IDs from file if provided
        if bulk_file:
            try:
                with open(bulk_file, 'r') as f:
                    file_ids = [line.strip() for line in f if line.strip()]
                client_ids.extend(file_ids)
                self.stdout.write(f"Loaded {len(file_ids)} client IDs from {bulk_file}")
            except FileNotFoundError:
                raise CommandError(f"File not found: {bulk_file}")

        if not client_ids:
            self.stdout.write("No client IDs provided. Use --help for usage information.")
            return

        # Remove duplicates while preserving order
        client_ids = list(dict.fromkeys(client_ids))

        self.stdout.write(f"\n{'='*60}")
        self.stdout.write(f"CLIENT DELETION OPERATION")
        self.stdout.write(f"{'='*60}")
        self.stdout.write(f"Mode: {mode.upper()}")
        self.stdout.write(f"Dry Run: {'YES' if dry_run else 'NO'}")
        self.stdout.write(f"Client IDs: {len(client_ids)}")
        self.stdout.write(f"{'='*60}\n")

        # Validate and filter clients
        valid_clients = []
        for client_id in client_ids:
            try:
                client = CustomUser.objects.get(id=client_id, role='borrower')
                
                # Apply status filter
                if status_filter != 'all' and client.status != status_filter:
                    self.stdout.write(
                        self.style.WARNING(f"Skipping {client.get_full_name()} - status '{client.status}' doesn't match filter '{status_filter}'")
                    )
                    continue
                
                valid_clients.append(client)
                
            except CustomUser.DoesNotExist:
                self.stdout.write(
                    self.style.ERROR(f"Client not found: {client_id}")
                )

        if not valid_clients:
            self.stdout.write(self.style.WARNING("No valid clients found to process."))
            return

        # Show summary of what will be processed
        total_dependencies = 0
        for client in valid_clients:
            dependencies = get_client_dependencies(client)
            total_dependencies += dependencies.get('total', 0)
            
            self.stdout.write(f"\n📋 {client.get_full_name()} ({client.id})")
            self.stdout.write(f"   Status: {client.status}")
            self.stdout.write(f"   Related records: {dependencies.get('total', 0)}")
            
            if dependencies.get('total', 0) > 0:
                details = []
                for key, count in dependencies.items():
                    if key != 'total' and count > 0:
                        details.append(f"{key}: {count}")
                if details:
                    self.stdout.write(f"   Details: {', '.join(details)}")

        self.stdout.write(f"\n📊 SUMMARY:")
        self.stdout.write(f"   Clients to process: {len(valid_clients)}")
        self.stdout.write(f"   Total related records: {total_dependencies}")
        self.stdout.write(f"   Operation: {'DRY RUN - ' if dry_run else ''}{mode.upper()}")

        # Confirmation prompt
        if not force and not dry_run:
            self.stdout.write(f"\n⚠️  WARNING: This will {mode} {len(valid_clients)} client(s) and {total_dependencies} related records.")
            confirm = input("Are you sure you want to continue? (yes/no): ")
            if confirm.lower() not in ['yes', 'y']:
                self.stdout.write("Operation cancelled.")
                return

        # Process clients
        self.stdout.write(f"\n🚀 Starting {'dry run' if dry_run else 'actual'} operation...\n")
        
        success_count = 0
        error_count = 0
        
        for i, client in enumerate(valid_clients, 1):
            self.stdout.write(f"[{i}/{len(valid_clients)}] Processing {client.get_full_name()}...")
            
            if dry_run:
                # Dry run - just show what would happen
                dependencies = get_client_dependencies(client)
                self.stdout.write(f"   ✓ Would {mode} client and {dependencies.get('total', 0)} related records")
                success_count += 1
            else:
                # Actual operation
                try:
                    if mode == 'blacklist':
                        success = self.blacklist_client(client)
                    else:
                        success, message = safe_delete_client_permanently(client, None)
                        if not success:
                            raise Exception(message)
                    
                    self.stdout.write(f"   ✅ Successfully {mode}ed {client.get_full_name()}")
                    success_count += 1
                    
                except Exception as e:
                    self.stdout.write(f"   ❌ Failed to {mode} {client.get_full_name()}: {str(e)}")
                    error_count += 1

        # Final summary
        self.stdout.write(f"\n{'='*60}")
        self.stdout.write(f"OPERATION COMPLETE")
        self.stdout.write(f"{'='*60}")
        self.stdout.write(f"✅ Successful: {success_count}")
        if error_count > 0:
            self.stdout.write(f"❌ Failed: {error_count}")
        self.stdout.write(f"📊 Total processed: {success_count + error_count}")
        
        if dry_run:
            self.stdout.write(f"\n💡 This was a dry run. No actual changes were made.")
            self.stdout.write(f"   Run without --dry-run to perform the actual operation.")

    def blacklist_client(self, client):
        """Blacklist a client (soft delete)"""
        with transaction.atomic():
            client.status = 'blacklisted'
            client.is_active = False
            client.save()
            
            # Create audit log
            AuditLog.objects.create(
                user=None,  # System action
                action='blacklist',
                model_name='CustomUser',
                object_id=str(client.id),
                description=f'Client blacklisted via management command: {client.get_full_name()}'
            )
            
        return True
