"""
Simple script to create test loans in different branches
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import Branch, CustomUser
from loans.models import Loan
from decimal import Decimal
from datetime import timedelta
from django.utils import timezone
from django.db.models import Sum

print("=" * 80)
print("SIMPLE BRANCH TEST DATA CREATION")
print("=" * 80)

# Get branches (excluding Westlands which already has data)
branches = list(Branch.objects.filter(is_active=True).exclude(name='Westlands Branch').order_by('name')[:2])

if len(branches) < 2:
    print("❌ Need at least 2 more branches besides Westlands")
    exit(1)

print(f"\n✓ Will create loans in: {', '.join([b.name for b in branches])}")

# Create simple loans for each branch
for i, branch in enumerate(branches, 2):
    print(f"\n{'='*80}")
    print(f"Creating loan for: {branch.name}")
    print(f"{'='*80}")
    
    # Get or create borrower
    username = f"test_borrower_{i}"
    borrower, created = CustomUser.objects.get_or_create(
        username=username,
        defaults={
            'email': f"{username}@test.com",
            'first_name': 'Test',
            'last_name': f'User {i}',
            'phone_number': f'0700000{i:03d}',
            'role': 'borrower',
            'branch': branch,
            'status': 'active'
        }
    )
    
    if created:
        borrower.set_password('password123')
        borrower.save()
        print(f"  ✓ Created borrower: {borrower.username}")
    else:
        # Update branch if needed
        if borrower.branch != branch:
            borrower.branch = branch
            borrower.save()
        print(f"  ✓ Using existing borrower: {borrower.username}")
    
    # Create loan
    loan_amount = Decimal(str(20000 * i))
    interest = loan_amount * Decimal('0.15')
    processing_fee = loan_amount * Decimal('0.025')
    total = loan_amount + interest
    
    # Check if loan already exists
    existing_loan = Loan.objects.filter(borrower=borrower, status='active').first()
    
    if not existing_loan:
        loan = Loan.objects.create(
            borrower=borrower,
            principal_amount=loan_amount,
            interest_rate=Decimal('15.00'),
            processing_fee=processing_fee,
            interest_amount=interest,
            total_amount=total,
            disbursement_date=timezone.now().date(),
            due_date=(timezone.now() + timedelta(days=90)).date(),
            status='active'
        )
        print(f"  ✓ Created loan:")
        print(f"    - Principal: KES {loan_amount:,.2f}")
        print(f"    - Interest: KES {interest:,.2f}")
        print(f"    - Total: KES {total:,.2f}")
    else:
        print(f"  ✓ Loan already exists for this borrower")

# Show summary
print(f"\n{'='*80}")
print("SUMMARY BY BRANCH")
print(f"{'='*80}")

all_branches = Branch.objects.filter(is_active=True)
for branch in all_branches:
    loans = Loan.objects.filter(borrower__branch=branch, status='active')
    count = loans.count()
    total = loans.aggregate(total=Sum('principal_amount'))['total'] or 0
    print(f"\n{branch.name}:")
    print(f"  - Active Loans: {count}")
    print(f"  - Portfolio Value: KES {total:,.2f}")

all_loans = Loan.objects.filter(status='active')
all_count = all_loans.count()
all_total = all_loans.aggregate(total=Sum('principal_amount'))['total'] or 0
print(f"\nAll Branches Combined:")
print(f"  - Active Loans: {all_count}")
print(f"  - Portfolio Value: KES {all_total:,.2f}")

print(f"\n{'='*80}")
print("✓ TEST DATA READY")
print(f"{'='*80}")
print("\nNow test in the dashboard:")
print("1. Login as admin (username: admin)")
print("2. Go to Reports & Statements Dashboard")
print("3. Use the 'Filter by Branch' dropdown")
print("4. You should see different numbers for each branch!")
