
from django.core.management.base import BaseCommand
from django.utils import timezone
from billing.services import AutoBillingService
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Run automated billing cycle tasks'
    
    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'Starting billing cycle at {timezone.now()}'
            )
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('Running in DRY-RUN mode - no changes will be made')
            )
            return
        
        try:
            results = AutoBillingService.run_daily_billing_tasks()
            
            self.stdout.write(
                self.style.SUCCESS(
                    f'Billing cycle completed successfully:\n'
                    f'- Renewed: {results["expired_services"]["renewed"]} services\n'
                    f'- Suspended: {results["expired_services"]["suspended"]} services\n'
                    f'- Failed: {results["expired_services"]["failed"]} services\n'
                    f'- Upcoming invoices created: {results["upcoming_invoices"]}'
                )
            )
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Billing cycle failed: {str(e)}')
            )
            logger.error(f'Billing cycle error: {str(e)}', exc_info=True)
