"""
Management command to create test client data for testing portfolio features
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from decimal import Decimal
from datetime import datetime, timedelta
import random

from users.models import CustomUser, Branch
from loans.models import Loan, LoanProduct, Repayment


class Command(BaseCommand):
    help = 'Creates test client data with loans and repayments for testing'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clients',
            type=int,
            default=10,
            help='Number of test clients to create'
        )
        parser.add_argument(
            '--officer-email',
            type=str,
            default='loanofficer@gmail.com',
            help='Email of the loan officer to assign clients to'
        )

    def handle(self, *args, **options):
        num_clients = options['clients']
        officer_email = options['officer_email']
        
        # Get the loan officer
        try:
            loan_officer = CustomUser.objects.get(email=officer_email, role='loan_officer')
            self.stdout.write(self.style.SUCCESS(f'Found loan officer: {loan_officer.get_full_name()}'))
        except CustomUser.DoesNotExist:
            self.stdout.write(self.style.ERROR(f'Loan officer with email {officer_email} not found'))
            return
        
        # Get a default branch
        branch = loan_officer.branch or Branch.objects.first()
        if not branch:
            self.stdout.write(self.style.ERROR('No branch found. Please create a branch first.'))
            return
        
        # Get or create loan products
        try:
            loan_products = list(LoanProduct.objects.filter(is_active=True))
            if not loan_products:
                self.stdout.write(self.style.WARNING('No active loan products found. Creating default products...'))
                # Create default loan product
                loan_product = LoanProduct.objects.create(
                    name='Test Loan Product',
                    code='TEST',
                    interest_rate=Decimal('20.00'),
                    processing_fee=Decimal('2.00'),
                    min_amount=Decimal('5000.00'),
                    max_amount=Decimal('100000.00'),
                    min_duration=7,
                    max_duration=365,
                    is_active=True
                )
                loan_products = [loan_product]
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error getting loan products: {e}'))
            return
        
        # First names and last names for test data
        first_names = ['John', 'Jane', 'Michael', 'Sarah', 'David', 'Emily', 'James', 'Lisa', 'Robert', 'Jennifer', 
                       'William', 'Linda', 'Richard', 'Patricia', 'Joseph', 'Mary', 'Thomas', 'Barbara', 'Charles', 'Susan']
        last_names = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez',
                      'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson', 'Thomas', 'Taylor', 'Moore', 'Jackson', 'Martin']
        
        created_count = 0
        
        for i in range(num_clients):
            # Create unique client data
            first_name = random.choice(first_names)
            last_name = random.choice(last_names)
            phone = f'+25479{random.randint(1000000, 9999999)}'
            id_number = f'{random.randint(20000000, 39999999)}'
            
            # Check if client already exists
            if CustomUser.objects.filter(phone_number=phone).exists():
                continue
            
            try:
                # Create client
                username = f'{first_name.lower()}.{last_name.lower()}.{i}'
                client = CustomUser.objects.create(
                    username=username,
                    first_name=first_name,
                    last_name=last_name,
                    email=f'{username}@testclient.com',
                    phone_number=phone,
                    id_number=id_number,
                    role='borrower',
                    status='active',
                    branch=branch,
                    portfolio_manager=loan_officer,
                    county='Nairobi',
                    date_of_birth=datetime.now().date() - timedelta(days=random.randint(7300, 18250)),  # 20-50 years old
                    gender=random.choice(['M', 'F']),
                    marital_status=random.choice(['single', 'married', 'divorced', 'widowed']),
                    monthly_income=Decimal(str(random.randint(20000, 100000))),
                )
                client.set_password('testpass123')
                
                # Note: Loans need to be created through the loan application process
                # For now, just create the clients
                
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f'Created client {created_count}/{num_clients}: {client.get_full_name()}'))
                
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'Error creating client: {e}'))
                continue
        
        self.stdout.write(self.style.SUCCESS(f'\nSuccessfully created {created_count} test clients with loans!'))

