"""
Simple test to verify missed payments service functionality
"""

import os
import django

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

from django.utils import timezone
from datetime import timedelta
from decimal import Decimal
import uuid

from loans.models import Loan, LoanProduct, LoanApplication
from users.models import CustomUser
from reports.missed_payments_service import MissedPaymentsService


def test_missed_payments_service():
    """Test the missed payments service with a simple scenario"""
    print("\n" + "="*80)
    print("Testing Missed Payments Service")
    print("="*80)
    
    # Create test client
    username = f"test_user_{uuid.uuid4().hex[:8]}"
    client = CustomUser.objects.create_user(
        username=username,
        email=f"{username}@example.com",
        phone_number="+254700000001",
        first_name='Test',
        last_name='User'
    )
    print(f"\n✓ Created test client: {client.get_full_name()}")
    
    # Create loan product
    product = LoanProduct.objects.create(
        name=f'Test Product {uuid.uuid4().hex[:8]}',
        product_type='boost',
        description='Test product',
        min_amount=Decimal('1000'),
        max_amount=Decimal('50000'),
        interest_rate=Decimal('10.0'),
        processing_fee=Decimal('5.0'),
        min_duration=7,
        max_duration=90,
        available_repayment_methods=['monthly']
    )
    print(f"✓ Created loan product: {product.name}")
    
    today = timezone.now().date()
    
    # Create overdue loan (should be included in missed payments)
    application1 = LoanApplication.objects.create(
        borrower=client,
        loan_product=product,
        requested_amount=Decimal('10000'),
        requested_duration=30,
        purpose='Test',
        status='approved'
    )
    
    due_date_overdue = today - timedelta(days=15)
    loan1 = Loan.objects.create(
        application=application1,
        borrower=client,
        principal_amount=Decimal('10000'),
        interest_amount=Decimal('1000'),
        processing_fee=Decimal('500'),
        total_amount=Decimal('11500'),
        disbursement_date=due_date_overdue - timedelta(days=30),
        due_date=due_date_overdue,
        duration_days=30,
        status='active',
        is_deleted=False,
        is_rolled_over=False
    )
    print(f"✓ Created overdue loan: {loan1.loan_number} (due {due_date_overdue})")
    print(f"  Outstanding: KES {loan1.outstanding_amount:,.2f}")
    
    # Create current loan (should NOT be included)
    application2 = LoanApplication.objects.create(
        borrower=client,
        loan_product=product,
        requested_amount=Decimal('5000'),
        requested_duration=30,
        purpose='Test',
        status='approved'
    )
    
    due_date_future = today + timedelta(days=15)
    loan2 = Loan.objects.create(
        application=application2,
        borrower=client,
        principal_amount=Decimal('5000'),
        interest_amount=Decimal('500'),
        processing_fee=Decimal('250'),
        total_amount=Decimal('5750'),
        disbursement_date=today,
        due_date=due_date_future,
        duration_days=30,
        status='active',
        is_deleted=False,
        is_rolled_over=False
    )
    print(f"✓ Created current loan: {loan2.loan_number} (due {due_date_future})")
    
    # Test get_missed_payments_for_client
    print("\n" + "-"*80)
    print("Testing get_missed_payments_for_client()")
    print("-"*80)
    
    missed_payments = MissedPaymentsService.get_missed_payments_for_client(str(client.id))
    
    print(f"\nFound {len(missed_payments)} missed payment(s)")
    
    for payment in missed_payments:
        print(f"\n  Loan: {payment['loan_number']}")
        print(f"  Due Date: {payment['due_date']}")
        print(f"  Amount Due: KES {payment['amount_due']:,.2f}")
        print(f"  Days Overdue: {payment['days_overdue']}")
    
    # Verify results
    assert len(missed_payments) == 1, f"Expected 1 missed payment, got {len(missed_payments)}"
    assert missed_payments[0]['loan_number'] == loan1.loan_number
    assert missed_payments[0]['days_overdue'] == 15
    
    print("\n✓ Test passed: Only overdue loan with outstanding balance is included")
    
    # Test calculate_missed_payment_count
    print("\n" + "-"*80)
    print("Testing calculate_missed_payment_count()")
    print("-"*80)
    
    count = MissedPaymentsService.calculate_missed_payment_count(client)
    print(f"\nMissed payment count: {count}")
    
    assert count == 1, f"Expected count of 1, got {count}"
    print("✓ Test passed: Correct missed payment count")
    
    # Test get_clients_with_missed_payments
    print("\n" + "-"*80)
    print("Testing get_clients_with_missed_payments()")
    print("-"*80)
    
    clients = MissedPaymentsService.get_clients_with_missed_payments()
    
    print(f"\nFound {len(clients)} client(s) with missed payments")
    
    for client_data in clients:
        print(f"\n  Client: {client_data['client_name']}")
        print(f"  Missed Payments: {client_data['missed_payment_count']}")
        print(f"  Total Outstanding: KES {client_data['total_outstanding']:,.2f}")
    
    # Find our test client in the results
    test_client_found = any(c['client_id'] == str(client.id) for c in clients)
    assert test_client_found, "Test client not found in results"
    
    print("\n✓ Test passed: Client with missed payments is included")
    
    # Cleanup
    print("\n" + "-"*80)
    print("Cleaning up test data...")
    print("-"*80)
    
    loan1.delete()
    loan2.delete()
    application1.delete()
    application2.delete()
    product.delete()
    client.delete()
    
    print("✓ Cleanup complete")
    
    print("\n" + "="*80)
    print("ALL TESTS PASSED ✓")
    print("="*80)


if __name__ == '__main__':
    test_missed_payments_service()
