from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils import timezone
from decimal import Decimal
from datetime import timedelta
import uuid

from loans.models import LoanProduct, LoanApplication, Loan, Repayment
from reports.models import LoanScoring, SystemSettings

User = get_user_model()


class Command(BaseCommand):
    help = 'Load sample data for HAVEN GRAZURI ADVANCE'

    def handle(self, *args, **options):
        self.stdout.write('Loading sample data...')
        
        # Create system settings
        settings, created = SystemSettings.objects.get_or_create()
        if created:
            self.stdout.write('SUCCESS: System settings created')
        
        # Create loan products
        products_data = [
            {
                'name': 'Personal Loan',
                'product_type': 'personal',
                'description': 'Quick personal loans for emergency needs',
                'min_amount': 5000,
                'max_amount': 100000,
                'interest_rate': 24.0,
                'processing_fee': 5.0,
                'min_duration': 7,
                'max_duration': 30,
            },
            {
                'name': 'Business Advance',
                'product_type': 'business',
                'description': 'Business loans for entrepreneurs',
                'min_amount': 10000,
                'max_amount': 500000,
                'interest_rate': 18.0,
                'processing_fee': 3.0,
                'min_duration': 14,
                'max_duration': 90,
            },
            {
                'name': 'Salary Loan',
                'product_type': 'salary',
                'description': 'Salary-based loans for employees',
                'min_amount': 2000,
                'max_amount': 50000,
                'interest_rate': 15.0,
                'processing_fee': 2.0,
                'min_duration': 7,
                'max_duration': 30,
            },
        ]
        
        for product_data in products_data:
            product, created = LoanProduct.objects.get_or_create(
                name=product_data['name'],
                defaults=product_data
            )
            if created:
                self.stdout.write(f'SUCCESS: Loan product "{product.name}" created')
        
        # Create sample users
        users_data = [
            {
                'username': 'john_doe',
                'first_name': 'John',
                'last_name': 'Doe',
                'email': 'john.doe@example.com',
                'phone_number': '+254700123456',
                'role': 'borrower',
                'monthly_income': 50000,
                'employer': 'Tech Solutions Ltd',
            },
            {
                'username': 'jane_smith',
                'first_name': 'Jane',
                'last_name': 'Smith',
                'email': 'jane.smith@example.com',
                'phone_number': '+254700123457',
                'role': 'borrower',
                'monthly_income': 75000,
                'employer': 'Marketing Pro Ltd',
            },
            {
                'username': 'mike_wilson',
                'first_name': 'Mike',
                'last_name': 'Wilson',
                'email': 'mike.wilson@example.com',
                'phone_number': '+254700123458',
                'role': 'borrower',
                'monthly_income': 35000,
                'employer': 'Retail Store',
            },
            {
                'username': 'loan_officer',
                'first_name': 'Loan',
                'last_name': 'Officer',
                'email': 'officer@branch.com',
                'phone_number': '+254700123459',
                'role': 'loan_officer',
            },
        ]
        
        for user_data in users_data:
            user, created = User.objects.get_or_create(
                username=user_data['username'],
                defaults=user_data
            )
            if created:
                user.set_password('password123')
                user.save()
                self.stdout.write(f'SUCCESS: User "{user.get_full_name()}" created')
        
        # Create loan applications
        personal_product = LoanProduct.objects.get(name='Personal Loan')
        business_product = LoanProduct.objects.get(name='Business Advance')
        
        borrowers = User.objects.filter(role='borrower')
        
        applications_data = [
            {
                'borrower': borrowers[0],
                'loan_product': personal_product,
                'requested_amount': 25000,
                'requested_duration': 14,
                'purpose': 'Emergency medical expenses',
                'status': 'approved',
            },
            {
                'borrower': borrowers[1],
                'loan_product': business_product,
                'requested_amount': 100000,
                'requested_duration': 30,
                'purpose': 'Business expansion',
                'status': 'pending',
            },
            {
                'borrower': borrowers[2],
                'loan_product': personal_product,
                'requested_amount': 15000,
                'requested_duration': 21,
                'purpose': 'School fees payment',
                'status': 'approved',
            },
        ]
        
        for app_data in applications_data:
            application, created = LoanApplication.objects.get_or_create(
                borrower=app_data['borrower'],
                loan_product=app_data['loan_product'],
                requested_amount=app_data['requested_amount'],
                defaults=app_data
            )
            if created:
                self.stdout.write(f'SUCCESS: Loan application for {application.borrower.get_full_name()} created')
        
        # Create active loans
        approved_applications = LoanApplication.objects.filter(status='approved')
        
        for application in approved_applications:
            loan, created = Loan.objects.get_or_create(
                application=application,
                defaults={
                    'borrower': application.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() - timedelta(days=10),
                    'due_date': timezone.now() + timedelta(days=application.requested_duration - 10),
                    'duration_days': application.requested_duration,
                }
            )
            if created:
                self.stdout.write(f'SUCCESS: Loan {loan.loan_number} created for {loan.borrower.get_full_name()}')
        
        # Create some repayments
        active_loans = Loan.objects.filter(status='active')
        
        for loan in active_loans[:2]:  # Only for first 2 loans
            repayment, created = Repayment.objects.get_or_create(
                loan=loan,
                amount=loan.total_amount * Decimal('0.3'),  # 30% payment
                defaults={
                    'payment_method': 'mpesa',
                    'mpesa_phone_number': loan.borrower.phone_number,
                }
            )
            if created:
                self.stdout.write(f'SUCCESS: Repayment recorded for loan {loan.loan_number}')
        
        # Create credit scores
        for borrower in borrowers:
            scoring, created = LoanScoring.objects.get_or_create(
                user=borrower,
                defaults={
                    'repayment_history_score': 25,
                    'income_score': 20,
                    'rollover_frequency_score': 15,
                    'employment_stability_score': 20,
                }
            )
            if created:
                scoring.calculate_score()
                self.stdout.write(f'SUCCESS: Credit score created for {borrower.get_full_name()}')
        
        self.stdout.write(self.style.SUCCESS('Sample data loaded successfully!'))
        self.stdout.write('You can now login to the admin interface with:')
        self.stdout.write('Username: phin')
        self.stdout.write('Password: (the one you set during superuser creation)') 