from django.core.management.base import BaseCommand
from django.utils import timezone
from users.models import CustomUser, PortfolioAssignment
from loans.models import Loan, LoanApplication
from decimal import Decimal
import random


class Command(BaseCommand):
    help = 'Set up demo portfolio data for testing'

    def add_arguments(self, parser):
        parser.add_argument(
            '--reset',
            action='store_true',
            help='Reset all portfolio assignments before creating demo data',
        )

    def handle(self, *args, **options):
        if options['reset']:
            self.stdout.write("Resetting portfolio assignments...")
            CustomUser.objects.filter(role='borrower').update(
                portfolio_manager=None,
                assigned_date=None
            )
            PortfolioAssignment.objects.all().delete()

        self.stdout.write("Setting up portfolio demo data...")

        # Get or create loan officers
        loan_officers = []
        officer_names = [
            ('John', 'Kamau', 'john.kamau@example.com'),
            ('Mary', 'Wanjiku', 'mary.wanjiku@example.com'),
            ('Peter', 'Ochieng', 'peter.ochieng@example.com'),
            ('Grace', 'Akinyi', 'grace.akinyi@example.com'),
        ]

        for first_name, last_name, email in officer_names:
            officer, created = CustomUser.objects.get_or_create(
                email=email,
                defaults={
                    'username': email.split('@')[0],
                    'first_name': first_name,
                    'last_name': last_name,
                    'role': 'loan_officer',
                    'phone_number': f'+254{random.randint(700000000, 799999999)}',
                    'status': 'active',
                    'is_verified': True,
                }
            )
            loan_officers.append(officer)
            if created:
                self.stdout.write(f"Created loan officer: {officer.get_full_name()}")

        # Get unassigned borrowers
        unassigned_borrowers = CustomUser.objects.filter(
            role='borrower',
            status='active',
            portfolio_manager__isnull=True
        )

        if not unassigned_borrowers.exists():
            self.stdout.write("No unassigned borrowers found. Creating some demo borrowers...")
            
            # Create demo borrowers
            counties = ['Nairobi', 'Kiambu', 'Nakuru', 'Mombasa', 'Kisumu', 'Eldoret']
            business_types = ['Retail Shop', 'Restaurant', 'Transport', 'Agriculture', 'Services']
            
            for i in range(20):
                borrower = CustomUser.objects.create(
                    username=f'borrower_{i+1:03d}',
                    first_name=f'Client{i+1}',
                    last_name=random.choice(['Mwangi', 'Njeri', 'Ochieng', 'Akinyi', 'Kiprop', 'Wanjiku']),
                    email=f'client{i+1}@example.com',
                    phone_number=f'+254{random.randint(700000000, 799999999)}',
                    role='borrower',
                    status='active',
                    county=random.choice(counties),
                    business_name=f'{random.choice(business_types)} Business {i+1}',
                    business_type=random.choice(business_types),
                    monthly_income=Decimal(random.randint(20000, 100000)),
                    is_verified=True,
                )
                unassigned_borrowers = CustomUser.objects.filter(
                    role='borrower',
                    status='active',
                    portfolio_manager__isnull=True
                )

        # Assign borrowers to loan officers using round-robin
        borrowers_list = list(unassigned_borrowers)
        assigned_count = 0

        for i, borrower in enumerate(borrowers_list):
            officer = loan_officers[i % len(loan_officers)]
            
            # Assign borrower to officer
            borrower.assign_to_portfolio_manager(officer)
            
            # Create portfolio assignment record
            PortfolioAssignment.objects.create(
                client=borrower,
                portfolio_manager=officer,
                assigned_by=loan_officers[0],  # First officer as admin
                reason='Demo data setup - Round robin assignment'
            )
            
            assigned_count += 1

        self.stdout.write(f"Assigned {assigned_count} borrowers to {len(loan_officers)} loan officers")

        # Create some demo loans for portfolio statistics
        self.stdout.write("Creating demo loans for portfolio statistics...")
        
        from loans.models import LoanProduct
        
        # Get or create a loan product
        loan_product, created = LoanProduct.objects.get_or_create(
            name='Demo Business Loan',
            defaults={
                'product_type': 'boost',
                'description': 'Demo loan product for portfolio testing',
                'min_amount': Decimal('5000'),
                'max_amount': Decimal('100000'),
                'interest_rate': Decimal('15.0'),
                'processing_fee': Decimal('5.0'),
                'min_duration': 30,
                'max_duration': 365,
                'duration_months': 6,
                'available_repayment_methods': ['monthly'],
                'is_active': True,
            }
        )

        # Create demo loan applications and loans
        assigned_borrowers = CustomUser.objects.filter(
            role='borrower',
            portfolio_manager__isnull=False
        )

        loans_created = 0
        for borrower in assigned_borrowers[:15]:  # Create loans for first 15 borrowers
            # Create loan application
            application = LoanApplication.objects.create(
                borrower=borrower,
                loan_product=loan_product,
                requested_amount=Decimal(random.randint(10000, 50000)),
                requested_duration=random.choice([90, 180, 270, 365]),
                purpose='Business expansion - Demo data',
                status='approved',
                auto_approved=True,
            )

            # Create loan
            loan = Loan.objects.create(
                application=application,
                borrower=borrower,
                principal_amount=application.requested_amount,
                interest_amount=application.interest_amount,
                processing_fee=application.processing_fee_amount,
                total_amount=application.total_amount,
                disbursement_date=timezone.now() - timezone.timedelta(days=random.randint(1, 180)),
                due_date=timezone.now() + timezone.timedelta(days=random.randint(30, 365)),
                duration_days=application.requested_duration,
                status=random.choice(['active', 'active', 'active', 'paid', 'defaulted']),
                amount_paid=Decimal(random.randint(0, int(application.total_amount))),
            )
            
            loans_created += 1

        self.stdout.write(f"Created {loans_created} demo loans")

        # Display portfolio summary
        self.stdout.write("\n" + "="*50)
        self.stdout.write("PORTFOLIO SUMMARY")
        self.stdout.write("="*50)

        for officer in loan_officers:
            stats = officer.get_portfolio_stats()
            if stats:
                self.stdout.write(f"\n{officer.get_full_name()}:")
                self.stdout.write(f"  Clients: {stats['total_clients']}")
                self.stdout.write(f"  Active Loans: {stats['active_loans']}")
                self.stdout.write(f"  Total Disbursed: KES {stats['total_disbursed']:,.2f}")
                self.stdout.write(f"  Collection Rate: {stats['collection_rate']:.1f}%")
                self.stdout.write(f"  Default Rate: {stats['default_rate']:.1f}%")

        self.stdout.write(f"\n{self.style.SUCCESS('Portfolio demo data setup completed!')}")
        self.stdout.write("You can now access the portfolio dashboard to see the demo data.")