"""
Management command to schedule periodic credit score updates
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from utils.credit_score_calculator import CreditScoreCalculator
from django.utils import timezone
from datetime import timedelta
import logging

User = get_user_model()
logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Schedule periodic credit score updates for borrowers with recent activity'

    def add_arguments(self, parser):
        parser.add_argument(
            '--days',
            type=int,
            default=7,
            help='Update scores for borrowers with activity in the last N days (default: 7)',
        )
        parser.add_argument(
            '--force-all',
            action='store_true',
            help='Force update all borrowers regardless of recent activity',
        )

    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS('📅 Starting Scheduled Credit Score Updates')
        )
        
        days = options['days']
        force_all = options['force_all']
        
        if force_all:
            # Update all borrowers
            users = User.objects.filter(role='borrower')
            self.stdout.write(f'🔄 Updating all {users.count()} borrowers (forced)')
        else:
            # Only update borrowers with recent activity
            cutoff_date = timezone.now() - timedelta(days=days)
            
            # Find borrowers with recent loan activity
            from loans.models import Loan, LoanApplication, Repayment
            
            recent_loan_users = set()
            
            # Users with recent loans
            recent_loans = Loan.objects.filter(created_at__gte=cutoff_date)
            recent_loan_users.update(recent_loans.values_list('borrower_id', flat=True))
            
            # Users with recent applications
            recent_applications = LoanApplication.objects.filter(submitted_at__gte=cutoff_date)
            recent_loan_users.update(recent_applications.values_list('borrower_id', flat=True))
            
            # Users with recent repayments
            recent_repayments = Repayment.objects.filter(payment_date__gte=cutoff_date)
            recent_loan_users.update(recent_repayments.values_list('loan__borrower_id', flat=True))
            
            if recent_loan_users:
                users = User.objects.filter(id__in=recent_loan_users, role='borrower')
                self.stdout.write(f'🎯 Found {users.count()} borrowers with activity in last {days} days')
            else:
                self.stdout.write(f'ℹ️  No borrowers with recent activity in last {days} days')
                return
        
        if not users.exists():
            self.stdout.write('ℹ️  No users to update')
            return
        
        # Update credit scores
        updated_count = 0
        error_count = 0
        
        for user in users:
            try:
                old_score = None
                try:
                    from reports.models import LoanScoring
                    old_score_obj = LoanScoring.objects.get(user=user)
                    old_score = old_score_obj.total_score
                except LoanScoring.DoesNotExist:
                    pass
                
                # Update credit score
                credit_score = CreditScoreCalculator.update_credit_score(user)
                
                if credit_score:
                    new_score = credit_score.total_score
                    
                    if old_score is not None and old_score != new_score:
                        change = new_score - old_score
                        change_str = f"({'+' if change > 0 else ''}{change})"
                        self.stdout.write(f'📈 {user.get_full_name()}: {old_score}  to  {new_score} {change_str}')
                    elif old_score is None:
                        self.stdout.write(f'🆕 {user.get_full_name()}: New score {new_score}')
                    else:
                        self.stdout.write(f'➡️  {user.get_full_name()}: Score unchanged ({new_score})')
                    
                    updated_count += 1
                else:
                    self.stdout.write(
                        self.style.ERROR(f'ERROR: Failed to update {user.get_full_name()}')
                    )
                    error_count += 1
                    
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'ERROR: Error updating {user.get_full_name()}: {str(e)}')
                )
                error_count += 1
        
        # Summary
        self.stdout.write('\n' + '='*50)
        self.stdout.write(
            self.style.SUCCESS(f'SUCCESS: SCHEDULED UPDATE COMPLETE')
        )
        self.stdout.write(f'📊 Updated: {updated_count}')
        if error_count > 0:
            self.stdout.write(f'ERROR: Errors: {error_count}')
        
        # Log the update
        logger.info(f'Scheduled credit score update completed: {updated_count} updated, {error_count} errors')
        
        self.stdout.write('='*50)