
from django.core.management.base import BaseCommand
from django.utils import timezone
from customers.models import Customer
from customers.services import CustomerServiceManager
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Process expired trial periods and activate/suspend services'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Run in dry-run mode without making changes',
        )
    
    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Processing trial periods at {timezone.now()}'
            )
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('Running in DRY-RUN mode - no changes will be made')
            )
        
        # Find customers with expired trials
        expired_trials = Customer.objects.filter(
            service_status='trial',
            trial_end_date__lte=timezone.now()
        )
        
        processed = 0
        activated = 0
        suspended = 0
        
        for customer in expired_trials:
            if not dry_run:
                try:
                    result = CustomerServiceManager.process_trial_completion(customer)
                    if result['success']:
                        if 'service_end' in result:
                            activated += 1
                            self.stdout.write(
                                self.style.SUCCESS(
                                    f'Activated service for {customer.customer_id}'
                                )
                            )
                        else:
                            suspended += 1
                            self.stdout.write(
                                self.style.WARNING(
                                    f'Suspended service for {customer.customer_id} - insufficient balance'
                                )
                            )
                    else:
                        self.stdout.write(
                            self.style.ERROR(
                                f'Failed to process {customer.customer_id}: {result["message"]}'
                            )
                        )
                    processed += 1
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f'Error processing {customer.customer_id}: {str(e)}')
                    )
                    logger.error(f'Trial processing error for {customer.customer_id}: {str(e)}', exc_info=True)
            else:
                # Dry run - just show what would happen
                total_required = customer.service.price + customer.service.installation_fee
                if customer.account_balance >= total_required:
                    self.stdout.write(f'WOULD ACTIVATE: {customer.customer_id} (Balance: {customer.account_balance})')
                    activated += 1
                else:
                    self.stdout.write(f'WOULD SUSPEND: {customer.customer_id} (Balance: {customer.account_balance}, Required: {total_required})')
                    suspended += 1
                processed += 1
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Trial processing completed:\n'
                f'- Processed: {processed} customers\n'
                f'- Activated: {activated} services\n'
                f'- Suspended: {suspended} services'
            )
        )
