"""
Django management command to check M-Pesa transaction status
Shows detailed information about all recent transactions
"""
from django.core.management.base import BaseCommand
from loans.models import MpesaTransaction
from django.utils import timezone
from datetime import timedelta


class Command(BaseCommand):
    help = 'Check status of M-Pesa transactions'

    def add_arguments(self, parser):
        parser.add_argument(
            '--days',
            type=int,
            default=7,
            help='Number of days to look back (default: 7)',
        )
        parser.add_argument(
            '--all',
            action='store_true',
            help='Show all transactions regardless of status',
        )

    def handle(self, *args, **options):
        days = options['days']
        show_all = options['all']
        
        self.stdout.write(self.style.SUCCESS('='*70))
        self.stdout.write(self.style.SUCCESS('M-Pesa Transaction Status Check'))
        self.stdout.write(self.style.SUCCESS('='*70))
        
        # Get recent transactions
        cutoff_date = timezone.now() - timedelta(days=days)
        transactions = MpesaTransaction.objects.filter(
            created_at__gte=cutoff_date
        ).order_by('-created_at')
        
        if not show_all:
            # Show only problematic ones
            transactions = transactions.filter(
                status__in=['pending', 'validated', 'confirmed', 'failed']
            )
        
        count = transactions.count()
        self.stdout.write(f'\nFound {count} transaction(s) in the last {days} days\n')
        
        if count == 0:
            self.stdout.write(self.style.SUCCESS('No transactions found.'))
            return
        
        # Display each transaction
        for t in transactions:
            self.stdout.write('='*70)
            self.stdout.write(f'Transaction ID: {t.id}')
            self.stdout.write(f'M-Pesa Trans ID: {t.trans_id or "N/A"}')
            self.stdout.write(f'Amount: KES {t.amount}')
            self.stdout.write(f'Phone: {t.phone_number or t.msisdn or "N/A"}')
            self.stdout.write(f'Date: {t.created_at}')
            self.stdout.write(f'Status: {t.status}')
            
            # Matching status
            if t.borrower:
                self.stdout.write(self.style.SUCCESS(f'✓ Borrower: {t.borrower.get_full_name()} (ID: {t.borrower.id})'))
            else:
                self.stdout.write(self.style.WARNING('✗ Borrower: NOT MATCHED'))
            
            if t.loan:
                self.stdout.write(self.style.SUCCESS(f'✓ Loan: {t.loan.loan_number} (ID: {t.loan.id})'))
            else:
                self.stdout.write(self.style.WARNING('✗ Loan: NOT MATCHED'))
            
            if t.repayment:
                self.stdout.write(self.style.SUCCESS(f'✓ Repayment: {t.repayment.receipt_number} (ID: {t.repayment.id})'))
            else:
                self.stdout.write(self.style.WARNING('✗ Repayment: NOT CREATED'))
            
            # Processing notes
            if t.processing_notes:
                self.stdout.write(f'Notes: {t.processing_notes}')
            
            # Processed timestamp
            if t.processed_at:
                self.stdout.write(f'Processed At: {t.processed_at}')
            
            # Payment source
            if t.payment_source:
                self.stdout.write(f'Payment Source: {t.payment_source}')
            
            # Show what needs to be done
            if not t.borrower or not t.loan or not t.repayment:
                self.stdout.write('\n' + self.style.WARNING('ACTION REQUIRED:'))
                if not t.borrower:
                    self.stdout.write('  → Need to match borrower by phone number')
                if not t.loan:
                    self.stdout.write('  → Need to match loan for this borrower')
                if not t.repayment:
                    self.stdout.write('  → Need to create repayment record')
                
                self.stdout.write('\nTo fix this transaction, run:')
                self.stdout.write(f'  python manage.py reprocess_mpesa_transaction {t.id}')
            else:
                self.stdout.write('\n' + self.style.SUCCESS('✓ Transaction fully processed'))
            
            self.stdout.write('')
        
        # Summary
        self.stdout.write('='*70)
        self.stdout.write('SUMMARY')
        self.stdout.write('='*70)
        
        matched_borrower = transactions.filter(borrower__isnull=False).count()
        matched_loan = transactions.filter(loan__isnull=False).count()
        has_repayment = transactions.filter(repayment__isnull=False).count()
        
        self.stdout.write(f'Total Transactions: {count}')
        self.stdout.write(f'Matched to Borrower: {matched_borrower}/{count}')
        self.stdout.write(f'Matched to Loan: {matched_loan}/{count}')
        self.stdout.write(f'Repayment Created: {has_repayment}/{count}')
        
        unprocessed = count - has_repayment
        if unprocessed > 0:
            self.stdout.write('\n' + self.style.WARNING(f'⚠ {unprocessed} transaction(s) need processing'))
            self.stdout.write('\nTo fix all unprocessed transactions:')
            self.stdout.write('  python manage.py fix_mpesa_payments')
        else:
            self.stdout.write('\n' + self.style.SUCCESS('✓ All transactions fully processed!'))
        
        self.stdout.write('\n')
