"""
Django management command to register Main Branch (4086675) callback URLs
"""
from django.core.management.base import BaseCommand, CommandError
from payments.branch_mpesa_service import BranchMpesaService
from users.models import Branch


class Command(BaseCommand):
    help = 'Register Main Branch (4086675) callback URLs with M-Pesa'

    def add_arguments(self, parser):
        parser.add_argument(
            '--skip-confirmation',
            action='store_true',
            help='Skip confirmation prompt',
        )

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=' * 70))
        self.stdout.write(self.style.SUCCESS('Main Branch M-Pesa URL Registration'))
        self.stdout.write(self.style.SUCCESS('=' * 70))
        
        try:
            # Get Main Branch
            main_branch = Branch.objects.get(mpesa_shortcode='4086675')
            
            self.stdout.write('')
            self.stdout.write(self.style.WARNING('Branch Information:'))
            self.stdout.write(f'  Name: {main_branch.name}')
            self.stdout.write(f'  Code: {main_branch.code}')
            self.stdout.write(f'  Shortcode: {main_branch.mpesa_shortcode}')
            self.stdout.write('')
            self.stdout.write(self.style.WARNING('Callback URLs:'))
            self.stdout.write('  Validation: https://branchbusinessadvance.co.ke/payments/callback/main/validation/')
            self.stdout.write('  Confirmation: https://branchbusinessadvance.co.ke/payments/callback/main/confirmation/')
            self.stdout.write('')
            
            # Confirm before proceeding
            if not options['skip_confirmation']:
                self.stdout.write(self.style.ERROR('⚠️  WARNING: You are about to register URLs in PRODUCTION!'))
                confirm = input('Type "yes" to continue: ')
                if confirm.lower() != 'yes':
                    self.stdout.write(self.style.WARNING('Registration cancelled.'))
                    return
            
            # Initialize service
            self.stdout.write('Initializing M-Pesa service...')
            service = BranchMpesaService(main_branch)
            
            # Register URLs
            self.stdout.write('Registering callback URLs with M-Pesa...')
            result = service.register_c2b_urls()
            
            # Display result
            self.stdout.write('')
            self.stdout.write(self.style.SUCCESS('=' * 70))
            self.stdout.write(self.style.SUCCESS('✓ URL Registration Successful!'))
            self.stdout.write(self.style.SUCCESS('=' * 70))
            self.stdout.write('')
            self.stdout.write('Response from M-Pesa:')
            self.stdout.write(str(result))
            self.stdout.write('')
            
            self.stdout.write(self.style.SUCCESS('Next Steps:'))
            self.stdout.write('1. Test by making a payment to paybill 4086675')
            self.stdout.write('2. Monitor callback logs at /payments/callbacks/')
            self.stdout.write('3. Check transactions at /payments/transactions/')
            self.stdout.write('')
            
        except Branch.DoesNotExist:
            raise CommandError('Main Branch with shortcode 4086675 not found in database')
        except Exception as e:
            self.stdout.write('')
            self.stdout.write(self.style.ERROR('=' * 70))
            self.stdout.write(self.style.ERROR('✗ URL Registration Failed'))
            self.stdout.write(self.style.ERROR('=' * 70))
            self.stdout.write(self.style.ERROR(f'Error: {str(e)}'))
            self.stdout.write('')
            raise CommandError(f'Failed to register URLs: {str(e)}')
