"""
Test script to verify interest income report implementation.
Tests filtering and aggregation functionality.
"""

import os
import sys

# Add project root to path
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

import django

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

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

from loans.models import Loan, LoanProduct, LoanApplication
from users.models import CustomUser
from django.db.models import Sum
from reports.filter_service import ReportFilterService


def test_interest_income_aggregation():
    """Test that interest income aggregation works correctly"""
    print("\n" + "="*80)
    print("Testing Interest Income Report Implementation")
    print("="*80)
    
    # Create test user
    user = CustomUser.objects.create_user(
        username=f'test_user_impl_{uuid.uuid4().hex[:8]}',
        email=f'testimpl_{uuid.uuid4().hex[:8]}@example.com',
        phone_number=f'+2547{uuid.uuid4().hex[:8]}',
        first_name='Test',
        last_name='User'
    )
    
    # Create test loan product
    product = LoanProduct.objects.create(
        name=f'Test Product Impl {uuid.uuid4().hex[:6]}',
        product_type='boost',
        description='Test product for implementation',
        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']
    )
    
    # Create test loans
    created_loans = []
    expected_total = Decimal('0.00')
    
    try:
        print("\n1. Creating test loans...")
        for i in range(5):
            interest = Decimal(str(1000 + (i * 500)))
            expected_total += interest
            
            # Create loan application
            application = LoanApplication.objects.create(
                borrower=user,
                loan_product=product,
                requested_amount=Decimal('10000.00'),
                requested_duration=30,
                purpose='Test purpose',
                status='approved'
            )
            
            # Create loan
            loan = Loan.objects.create(
                borrower=user,
                application=application,
                principal_amount=Decimal('10000.00'),
                interest_amount=interest,
                processing_fee=Decimal('500.00'),
                total_amount=Decimal('10000.00') + interest + Decimal('500.00'),
                disbursement_date=timezone.now().date() - timedelta(days=i),
                due_date=timezone.now().date() + timedelta(days=30),
                status='active',
                is_deleted=False,
                is_rolled_over=False
            )
            created_loans.append(loan)
            print(f"   Created loan {i+1} with interest: KES {interest}")
        
        print(f"\n2. Testing aggregation...")
        print(f"   Expected total interest: KES {expected_total}")
        
        # Test aggregation (Requirement 7.3)
        queryset = Loan.objects.filter(
            id__in=[loan.id for loan in created_loans],
            is_deleted=False,
            is_rolled_over=False,
            status='active'
        )
        
        calculated_total = queryset.aggregate(
            total=Sum('interest_amount')
        )['total'] or Decimal('0.00')
        
        print(f"   Calculated total interest: KES {calculated_total}")
        
        if calculated_total == expected_total:
            print("   ✓ Aggregation test PASSED!")
        else:
            print(f"   ✗ Aggregation test FAILED: {calculated_total} != {expected_total}")
            return False
        
        # Test date range filtering (Requirement 7.2)
        print(f"\n3. Testing date range filtering...")
        cutoff_date = timezone.now().date() - timedelta(days=2)
        filtered_qs = ReportFilterService.apply_date_range_filter(
            queryset, cutoff_date, timezone.now().date(), 'disbursement_date'
        )
        
        filtered_count = filtered_qs.count()
        print(f"   Filtered loans (last 3 days): {filtered_count}")
        
        if filtered_count == 3:  # Should have 3 loans in the last 3 days
            print("   ✓ Date range filtering test PASSED!")
        else:
            print(f"   ✗ Date range filtering test FAILED: expected 3, got {filtered_count}")
        
        # Test product filtering (Requirement 7.2)
        print(f"\n4. Testing product filtering...")
        product_filtered_qs = ReportFilterService.apply_loan_product_filter(
            queryset, str(product.id)
        )
        
        product_filtered_count = product_filtered_qs.count()
        print(f"   Filtered loans by product: {product_filtered_count}")
        
        if product_filtered_count == 5:  # All loans should match
            print("   ✓ Product filtering test PASSED!")
        else:
            print(f"   ✗ Product filtering test FAILED: expected 5, got {product_filtered_count}")
        
        # Test exclusion of rolled-over loans
        print(f"\n5. Testing rolled-over loan exclusion...")
        created_loans[0].is_rolled_over = True
        created_loans[0].save()
        
        active_qs = Loan.objects.filter(
            id__in=[loan.id for loan in created_loans],
            is_deleted=False,
            is_rolled_over=False,
            status='active'
        )
        
        active_count = active_qs.count()
        print(f"   Active loans (excluding rolled-over): {active_count}")
        
        if active_count == 4:  # Should have 4 active loans
            print("   ✓ Rolled-over exclusion test PASSED!")
        else:
            print(f"   ✗ Rolled-over exclusion test FAILED: expected 4, got {active_count}")
        
        print("\n" + "="*80)
        print("ALL TESTS PASSED!")
        print("="*80)
        return True
        
    finally:
        # Cleanup
        print("\nCleaning up test data...")
        for loan in created_loans:
            if hasattr(loan, 'application') and loan.application:
                loan.application.delete()
            loan.delete()
        product.delete()
        user.delete()
        print("Cleanup complete.")


if __name__ == '__main__':
    try:
        success = test_interest_income_aggregation()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n✗ TEST FAILED WITH ERROR: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
