"""
Management command to update credit scores for all borrowers
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from utils.credit_score_calculator import CreditScoreCalculator

User = get_user_model()

class Command(BaseCommand):
    help = 'Update credit scores for all borrowers based on their loan history'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user-id',
            type=str,
            help='Update credit score for specific user ID',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be updated without making changes',
        )

    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS('🔄 Starting Credit Score Update Process')
        )
        
        # Get users to update
        if options['user_id']:
            try:
                users = User.objects.filter(id=options['user_id'], role='borrower')
                if not users.exists():
                    self.stdout.write(
                        self.style.ERROR(f'ERROR: User with ID {options["user_id"]} not found or not a borrower')
                    )
                    return
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'ERROR: Error finding user: {str(e)}')
                )
                return
        else:
            users = User.objects.filter(role='borrower')
        
        total_users = users.count()
        self.stdout.write(f'📊 Found {total_users} borrowers to process')
        
        if options['dry_run']:
            self.stdout.write(
                self.style.WARNING('🔍 DRY RUN MODE - No changes will be made')
            )
        
        updated_count = 0
        error_count = 0
        
        for user in users:
            try:
                # Calculate scores
                scores = CreditScoreCalculator.calculate_total_score(user)
                
                self.stdout.write(f'\n👤 {user.get_full_name()} ({user.username})')
                self.stdout.write(f'   📈 Repayment History: {scores["repayment_history_score"]}/40')
                self.stdout.write(f'   💰 Income Stability: {scores["income_score"]}/25')
                self.stdout.write(f'   🔄 Rollover Frequency: {scores["rollover_frequency_score"]}/20')
                self.stdout.write(f'   💼 Employment Stability: {scores["employment_stability_score"]}/15')
                self.stdout.write(f'   🎯 Total Score: {scores["total_score"]}/100')
                
                # Determine risk level
                if scores['total_score'] >= 80:
                    risk_level = 'Low Risk'
                    credit_limit = 500000
                elif scores['total_score'] >= 60:
                    risk_level = 'Medium Risk'
                    credit_limit = 200000
                else:
                    risk_level = 'High Risk'
                    credit_limit = 50000
                
                self.stdout.write(f'   WARNING:  Risk Level: {risk_level}')
                self.stdout.write(f'   💳 Credit Limit: KES {credit_limit:,}')
                
                if not options['dry_run']:
                    # Actually update the score
                    credit_score = CreditScoreCalculator.update_credit_score(user)
                    if credit_score:
                        updated_count += 1
                        self.stdout.write(
                            self.style.SUCCESS('   SUCCESS: Credit score updated')
                        )
                    else:
                        error_count += 1
                        self.stdout.write(
                            self.style.ERROR('   ERROR: Failed to update credit score')
                        )
                else:
                    self.stdout.write(
                        self.style.WARNING('   🔍 Would update (dry run)')
                    )
                    
            except Exception as e:
                error_count += 1
                self.stdout.write(
                    self.style.ERROR(f'   ERROR: Error processing {user.get_full_name()}: {str(e)}')
                )
        
        # Summary
        self.stdout.write('\n' + '='*50)
        if options['dry_run']:
            self.stdout.write(
                self.style.SUCCESS(f'🔍 DRY RUN COMPLETE')
            )
            self.stdout.write(f'📊 Would update {total_users - error_count} credit scores')
        else:
            self.stdout.write(
                self.style.SUCCESS(f'SUCCESS: CREDIT SCORE UPDATE COMPLETE')
            )
            self.stdout.write(f'📊 Updated: {updated_count}')
        
        if error_count > 0:
            self.stdout.write(f'ERROR: Errors: {error_count}')
        
        self.stdout.write('='*50)