"""
Create test data across multiple branches to verify filtering
"""
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, LoanApplication, LoanProduct
from decimal import Decimal
from datetime import datetime, timedelta
from django.utils import timezone

print("=" * 80)
print("CREATING TEST DATA FOR BRANCH FILTERING")
print("=" * 80)

# Get branches
branches = list(Branch.objects.filter(is_active=True).order_by('name'))
print(f"\n✓ Found {len(branches)} active branches")

if len(branches) < 2:
    print("❌ Need at least 2 branches for testing")
    exit(1)

# Get or create loan product
loan_product, created = LoanProduct.objects.get_or_create(
    name="Test Product",
    defaults={
        'product_type': 'boost',
        'description': 'Test product for branch filtering',
        'interest_rate': Decimal('10.00'),
        'processing_fee': Decimal('2.50'),
        'min_amount': Decimal('5000'),
        'max_amount': Decimal('100000'),
        'min_duration': 30,
        'max_duration': 365,
        'duration_months': 3,
        'available_repayment_methods': ['monthly'],
        'is_active': True
    }
)
print(f"\n✓ Loan Product: {loan_product.name}")

# Create test borrowers and loans for each branch
for i, branch in enumerate(branches[:3], 1):  # Create for first 3 branches
    print(f"\n{'='*80}")
    print(f"Creating data for: {branch.name}")
    print(f"{'='*80}")
    
    # Create borrower
    username = f"borrower_{branch.code.lower()}_{i}"
    email = f"{username}@test.com"
    
    borrower, created = CustomUser.objects.get_or_create(
        username=username,
        defaults={
            'email': email,
            'first_name': f'Test',
            'last_name': f'Borrower {i}',
            'phone_number': f'07000000{i:02d}',
            'role': 'borrower',
            'branch': branch,
            'status': 'active'
        }
    )
    
    if created:
        borrower.set_password('password123')
        borrower.save()
        print(f"  ✓ Created borrower: {borrower.username}")
    else:
        print(f"  ✓ Using existing borrower: {borrower.username}")
    
    # Create loan application
    loan_amount = Decimal(str(10000 * i))
    
    application, created = LoanApplication.objects.get_or_create(
        borrower=borrower,
        loan_product=loan_product,
        defaults={
            'requested_amount': loan_amount,
            'duration': 90,
            'status': 'approved',
            'purpose': f'Test loan for {branch.name}'
        }
    )
    
    if created:
        print(f"  ✓ Created application for KES {loan_amount:,.2f}")
    else:
        print(f"  ✓ Using existing application for KES {loan_amount:,.2f}")
    
    # Create active loan
    processing_fee = loan_amount * Decimal('0.025')
    interest = loan_amount * Decimal('0.10')
    total_amount = loan_amount + interest
    
    loan, created = Loan.objects.get_or_create(
        borrower=borrower,
        application=application,
        defaults={
            'principal_amount': loan_amount,
            'interest_rate': Decimal('10.00'),
            'processing_fee': processing_fee,
            'interest_amount': interest,
            'total_amount': total_amount,
            'duration_days': 90,
            'disbursement_date': timezone.now().date(),
            'due_date': (timezone.now() + timedelta(days=90)).date(),
            'status': 'active'
        }
    )
    
    if created:
        print(f"  ✓ Created loan:")
        print(f"    - Principal: KES {loan_amount:,.2f}")
        print(f"    - Processing Fee: KES {processing_fee:,.2f}")
        print(f"    - Interest: KES {interest:,.2f}")
        print(f"    - Total: KES {total_amount:,.2f}")
    else:
        print(f"  ✓ Loan already exists for this borrower")

# Summary
print(f"\n{'='*80}")
print("SUMMARY")
print(f"{'='*80}")

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

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

print(f"\n{'='*80}")
print("✓ TEST DATA CREATED SUCCESSFULLY")
print(f"{'='*80}")
print("\nNow test the branch filter in the dashboard:")
print("1. Login as admin")
print("2. Go to Reports & Statements Dashboard")
print("3. Use the 'Filter by Branch' dropdown")
print("4. Verify the numbers change for each branch")
